Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
1
Indexable
Never
import { getStateStore } from 'src/global-state/Store';
import { convertParams } from './convertParams';
import { generatePermissions } from './generatePermissions';

const isUserHasPermissions = (requiredPermissions: string[]) => {
  const userPermissions = getStateStore().user.permissions;
  console.log({ userPermissions, requiredPermissions });
  return requiredPermissions.every((permission: string) => userPermissions.includes(permission));
};

const hasPermissions = (
  originalMethod: any,
  requiredPermissions: string[],
  expressionPermission?: string,
  replacementParams?: Record<string, any>,
  additionalParams?: Record<string, any>
) => {
  return function (...args: any[]) {
    if (expressionPermission) {
      replacementParams = convertParams(replacementParams, args);
      const templateArguments = {
        ...replacementParams,
        ...additionalParams,
      };
      requiredPermissions = generatePermissions(expressionPermission, templateArguments);
      console.log({ requiredPermissions });
    }
    const userPermissions = getStateStore().user.permissions;
    const hasRequiredPermissions = isUserHasPermissions(requiredPermissions);
    if (!hasRequiredPermissions) {
      console.error(`User does not have permission to perform this action: ${requiredPermissions.join(', ')}`);
      return;
    }
    return originalMethod.apply(this, args);
  };
};

export { hasPermissions, isUserHasPermissions };