Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 7x 33x 33x 33x 66x 33x 7x 14x 7x 7x 7x 7x 7x 7x 7x 7x 105x 33x 33x 33x 33x 33x 33x 33x 2x 2x 1x 1x 31x | import { AuthFacade } from '@/facades/auth.facade';
import { PermissionManager, PermissionModel, PermissionVerb } from '@/services/permissions.service';
import prisma from '@/services/prisma.service';
import HttpStatusCode from '@/utils/HTTPStatusCodes';
import { ResponseHandler } from '@/utils/responseHandler';
import { logger } from '@/utils/winston';
import { NextFunction, Request, Response } from 'express';
export function checkPermission(model: PermissionModel, ...actions: PermissionVerb[]) {
return async (_: Request, res: Response, next: NextFunction) => {
try {
const permissionManager = new PermissionManager();
const authBody = AuthFacade.get();
if (!authBody) {
const resBody = ResponseHandler.Unauthorized('Unauthenticated');
res.status(resBody.error!.code).json(resBody);
} else {
const user = await prisma.user.findUnique({
where: { id: authBody.userId },
include: {
role: {
include: { permission: true },
},
},
});
if (I!user) {
res.status(HttpStatusCode.UNAUTHORIZED).json(ResponseHandler.NotFound('User not found'));
} else {
if (user.role.permission) {
const hasPermission = permissionManager.canPerform(
user.role.permission?.name,
model,
actions
);
if (hasPermission) {
next();
} else {
res
I.status(HttpStatusCode.FORBIDDEN)
.json(ResponseHandler.Forbidden('Permission denied'));
}
} else {
next();
}
}
}
} catch (error) {
logger.error({ 'Error checking permission:': error });
res
.status(500)
.json(
ResponseHandler.response('Internal Server Error', HttpStatusCode.INTERNAL_SERVER_ERROR)
);
}
};
}
|