Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

1.9 KB
Raw Blame
import { isNil, Permission } from '@activepieces/core-utils';
import { ApEdition, ApFlagId, PlatformRole } from '@activepieces/shared';
import { useQuery } from '@tanstack/react-query';

import { authenticationApi } from '@/api/authentication-api';
import { platformApi } from '@/api/platforms-api';
import { flagsHooks } from '@/hooks/flags-hooks';
import { userHooks } from '@/hooks/user-hooks';
import { authenticationSession } from '@/lib/authentication-session';

export const useAuthorization = (projectId?: string) => {
  const { data: edition } = flagsHooks.useFlag(ApFlagId.EDITION);

  const platformId = authenticationSession.getPlatformId();
  const scopedProjectId = projectId ?? authenticationSession.getProjectId();
  const { data: projectRole, isLoading } = useQuery({
    queryKey: ['project-role', scopedProjectId],
    queryFn: async () => {
      const platform = await platformApi.getCurrentPlatform();
      if (platform.plan.projectRolesEnabled) {
        const projectRole = await authenticationApi.getCurrentProjectRole({
          projectId: scopedProjectId ?? '',
        });
        return projectRole;
      }
      return null;
    },
    retry: false,
    enabled:
      !isNil(edition) && edition !== ApEdition.COMMUNITY && !isNil(platformId),
  });

  const checkAccess = (permission: Permission) => {
    if (isLoading || edition === ApEdition.COMMUNITY) {
      return true;
    }

    return projectRole?.permissions?.includes(permission) ?? true;
  };

  return { checkAccess, isFetchingProjectRole: isLoading };
};

export const useIsPlatformAdmin = () => {
  const platformRole = userHooks.getCurrentUserPlatformRole();
  return platformRole === PlatformRole.ADMIN;
};

export const useIsPlatformPrivileged = () => {
  const platformRole = userHooks.getCurrentUserPlatformRole();
  return (
    platformRole === PlatformRole.ADMIN ||
    platformRole === PlatformRole.OPERATOR
  );
};