본문 바로가기

express

Permission check on user's actions [Express, Node]

There are some actions need permisstion or Authentication. Like Deleting, Updating, Getting information, adminning user. etc.

How we check permission or authentication?

We can make middleware doing permission checking. and put it in Router.

const { protect, authroize } = require('../middleware/auth');

router.use(protect);   // Here
router.use(authroize('admin'));   // Here

router
  .route('/')
  .get(getUsers)
  .post(createuser);

// check protect, authroize at all situation. get and post request

or

const { protect, authorize } = require('../middleware/auth');

router
  .route('/')
  .get(getCourses)
  .post(protect, authorize('publisher', 'admin'), createCourse);
  
// Only check at the request post not get request.

"protect" middleware checks if client has authorizaion token or not.

"authorize" middleware checks user's role have permission (for example, user cant delete, but admin can delete)

 

protect middleware

Because token is sent in request Headers or cookies, just check those. and verify token.

Token is made with document.id. so we can get id by verifying token.

// Protect routes
exports.protect = asyncHandler(async (req, res, next) => {
  let token;
  
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
  // Set token from Bearer token in header
  token = req.headers.authorization.split(' ')[1];
  } else if (req.cookies.token) {
    token = req.cookies.token;
  }
  
  // Make sure token exists
  if (!token) {
    return next(new ErrorResponse('Not authorized to access this route', 401));
  }
  
  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    req.user = await User.findById(decoded.id);
    
    next();
  } catch (err) {
    return next(new ErrorResponse('Not authorized to access this route', 401));
  }
});

authorize middleware

This limits access to inputed roles only. for example "authorize('publisher', 'admin')" : only publisher or admin can access.

// Grant access to specific roles
exports.authorize = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new ErrorResponse(
          `User role ${req.user.role) is not authorized to access this route`,
          403
        )
      );
    }
    next();
  );
};