authorizeRequest.middleware (1).js 908 B

1234567891011121314151617181920212223242526272829303132333435
  1. // middlewares/authorizeRequest.middleware
  2. import { getStatusCode, StatusCodes } from "http-status-codes";
  3. import ApplicationError from "../libs/errors/application.error.js";
  4. export default (allowedRoles, condition) => {
  5. return async (req, res, next) => {
  6. const user = req.user;
  7. if (!user) {
  8. throw new ApplicationError(
  9. getStatusCode(StatusCodes.UNAUTHORIZED),
  10. "Not authorized",
  11. StatusCodes.UNAUTHORIZED
  12. );
  13. }
  14. let isAllowed = Array.isArray(allowedRoles)
  15. ? allowedRoles.includes(user.role)
  16. : user.role === allowedRoles;
  17. if (condition && typeof condition === "function") {
  18. isAllowed = await condition(user, req);
  19. }
  20. if (isAllowed) {
  21. next();
  22. } else {
  23. throw new ApplicationError(
  24. getStatusCode(StatusCodes.FORBIDDEN),
  25. "Access is forbidden",
  26. StatusCodes.FORBIDDEN
  27. );
  28. }
  29. };
  30. };