UNPKG

@fdm-monster/server

Version:

FDM Monster is a bulk OctoPrint, Klipper, PrusaLink and BambuLab manager to set up, configure and monitor 3D printers. Our aim is to provide neat overview over your farm.

31 lines (30 loc) 1.93 kB
import { AuthenticationError, AuthorizationError } from "../exceptions/runtime.exceptions.js"; import { AUTH_ERROR_REASON } from "../constants/authorization.constants.js"; import { inject } from "awilix-express"; //#region src/middleware/authenticate.ts const authenticate = () => inject((authService, loggerFactory, settingsStore) => async (req, res, next) => { const logger = loggerFactory("Middleware:authenticate"); if (!await settingsStore.getLoginRequired()) return next(); if (req.user?.needsPasswordChange) throw new AuthenticationError("Password change required", AUTH_ERROR_REASON.PasswordChangeRequired); const bearer = req.headers.authorization?.replace("Bearer ", "") || void 0; if (!!bearer?.length && authService.isJwtTokenBlacklisted(bearer)) throw new AuthenticationError("Not authenticated", AUTH_ERROR_REASON.LoginRequired); if (req.isAuthenticated()) return next(); logger.log(`Not authenticated for route: ${req.originalUrl}`); throw new AuthenticationError("Not authenticated", AUTH_ERROR_REASON.InvalidOrExpiredAuthToken); }); function permission(requiredPermission) { return inject((permissionService, roleService) => async (req, _res, next) => { const userRoles = req.roles; if (!userRoles?.length) throw new AuthorizationError({ permissions: [requiredPermission] }); const assignedPermissions = roleService.getRolesPermissions(userRoles); if (!permissionService.authorizePermission(requiredPermission, assignedPermissions)) throw new AuthorizationError({ permissions: [requiredPermission] }); next(); }); } const authorizeRoles = (requiredRoles, subset = true) => inject((roleService) => async (req, res, next) => { if (!req.roles?.length || !roleService.authorizeRoles(requiredRoles, req.roles, subset)) throw new AuthorizationError({ roles: requiredRoles }); next(); }); //#endregion export { authenticate, authorizeRoles, permission }; //# sourceMappingURL=authenticate.js.map