Skip to content

The open alternative to Salesforce, designed for AI.

14.3 KB
Raw Blame
import { InjectRepository } from '@nestjs/typeorm';

import { msg } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
import { In, Not, Repository } from 'typeorm';

import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { type FlatWorkspaceMember } from 'src/engine/core-modules/user/types/flat-workspace-member.type';
import {
  PermissionsException,
  PermissionsExceptionCode,
  PermissionsExceptionMessage,
} from 'src/engine/permissions/permissions.exception';
import { RoleTargetEntity } from 'src/engine/metadata-modules/role-target/role-target.entity';
import { RoleTargetService } from 'src/engine/metadata-modules/role-target/services/role-target.service';
import { RoleAssignmentValidationService } from 'src/engine/permissions/role-assignment/services/role-assignment-validation.service';
import { RoleEntity } from 'src/engine/metadata-modules/role/role.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { STANDARD_ROLE } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-role.constant';
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';

export class UserRoleService {
  constructor(
    @InjectWorkspaceScopedRepository(RoleTargetEntity)
    private readonly roleTargetRepository: WorkspaceScopedRepository<RoleTargetEntity>,
    @InjectRepository(UserWorkspaceEntity)
    private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
    private readonly workspaceOrmManager: WorkspaceOrmManager,
    private readonly roleTargetService: RoleTargetService,
    private readonly workspaceCacheService: WorkspaceCacheService,
    private readonly roleAssignmentValidationService: RoleAssignmentValidationService,
  ) {}

  public async assignRoleToWorkspaceMember({
    workspaceId,
    workspaceMemberId,
    roleId,
    actingUserWorkspaceId,
  }: {
    workspaceId: string;
    workspaceMemberId: string;
    roleId: string;
    actingUserWorkspaceId?: string;
  }): Promise<{
    workspaceMember: WorkspaceMemberWorkspaceEntity;
    userWorkspaceId: string;
  }> {
    const workspaceMember = await this.getWorkspaceMemberByIdOrThrow({
      workspaceMemberId,
      workspaceId,
    });

    const userWorkspace = await this.userWorkspaceRepository.findOne({
      where: {
        userId: workspaceMember.userId,
        workspaceId,
      },
    });

    if (!isDefined(userWorkspace)) {
      throw new PermissionsException(
        PermissionsExceptionMessage.USER_WORKSPACE_NOT_FOUND,
        PermissionsExceptionCode.USER_WORKSPACE_NOT_FOUND,
      );
    }

    // Before role validation so a self-assignment reports the self-role error even for an unknown role
    this.validateNotSelfAssignmentOrThrow({
      userWorkspaceIds: [userWorkspace.id],
      actingUserWorkspaceId,
    });

    const { userWorkspaceRoleMap } =
      await this.workspaceCacheService.getOrRecompute(workspaceId, [
        'userWorkspaceRoleMap',
      ]);

    if (userWorkspaceRoleMap[userWorkspace.id] === roleId) {
      return { workspaceMember, userWorkspaceId: userWorkspace.id };
    }

    await this.roleAssignmentValidationService.validateRoleAssignableToUsersOrThrow(
      { roleId, workspaceId },
    );

    await this.assignRoleToManyUserWorkspace({
      workspaceId,
      userWorkspaceIds: [userWorkspace.id],
      roleId,
      actingUserWorkspaceId,
    });

    return { workspaceMember, userWorkspaceId: userWorkspace.id };
  }

  public async assignRoleToManyUserWorkspace({
    workspaceId,
    userWorkspaceIds,
    roleId,
    actingUserWorkspaceId,
  }: {
    workspaceId: string;
    userWorkspaceIds: string[];
    roleId: string;
    actingUserWorkspaceId?: string;
  }): Promise<void> {
    if (userWorkspaceIds.length === 0) {
      return;
    }

    this.validateNotSelfAssignmentOrThrow({
      userWorkspaceIds,
      actingUserWorkspaceId,
    });

    const userWorkspaceIdsToAssign =
      await this.validateAssignRoleInputsAndGetUserWorkspaceIdsToAssign({
        userWorkspaceIds,
        workspaceId,
        roleId,
      });

    if (userWorkspaceIdsToAssign.length === 0) {
      return;
    }

    await this.roleTargetService.createMany({
      createRoleTargetInputs: userWorkspaceIdsToAssign.map(
        (userWorkspaceId) => ({
          roleId,
          targetId: userWorkspaceId,
          targetMetadataForeignKey: 'userWorkspaceId' as const,
        }),
      ),
      workspaceId,
    });
  }

  public async getRoleIdForUserWorkspace({
    workspaceId,
    userWorkspaceId,
  }: {
    workspaceId: string;
    userWorkspaceId: string;
  }): Promise<string> {
    const { userWorkspaceRoleMap } =
      await this.workspaceCacheService.getOrRecompute(workspaceId, [
        'userWorkspaceRoleMap',
      ]);

    const roleId = userWorkspaceRoleMap[userWorkspaceId];

    if (!isDefined(roleId)) {
      throw new PermissionsException(
        `User workspace ${userWorkspaceId} has no role assigned`,
        PermissionsExceptionCode.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
      );
    }

    return roleId;
  }

  public async getRolesByUserWorkspaces({
    userWorkspaceIds,
    workspaceId,
  }: {
    userWorkspaceIds: string[];
    workspaceId: string;
  }): Promise<Map<string, RoleEntity[]>> {
    if (!userWorkspaceIds.length) {
      return new Map();
    }

    const allRoleTargets = await this.roleTargetRepository.find(workspaceId, {
      where: {
        userWorkspaceId: In(userWorkspaceIds),
      },
      relations: {
        role: {
          rolePermissionFlags: {
            permissionFlag: true,
          },
        },
      },
    });

    if (!allRoleTargets.length) {
      return new Map();
    }

    const rolesMap = new Map<string, RoleEntity[]>();

    for (const userWorkspaceId of userWorkspaceIds) {
      const roleTargetsOfUserWorkspace = allRoleTargets.filter(
        (roleTarget) => roleTarget.userWorkspaceId === userWorkspaceId,
      );

      const rolesOfUserWorkspace = roleTargetsOfUserWorkspace
        .map((roleTarget) => roleTarget.role)
        .filter(isDefined);

      rolesMap.set(userWorkspaceId, rolesOfUserWorkspace);
    }

    return rolesMap;
  }

  public async getWorkspaceMembersAssignedToRole(
    roleId: string,
    workspaceId: string,
  ): Promise<FlatWorkspaceMember[]> {
    const userWorkspaceIdsWithRole =
      await this.getUserWorkspaceIdsAssignedToRole(roleId, workspaceId);

    const { flatWorkspaceMemberMaps } =
      await this.workspaceCacheService.getOrRecompute(workspaceId, [
        'flatWorkspaceMemberMaps',
      ]);

    return userWorkspaceIdsWithRole
      .map((userWorkspaceId) => {
        const workspaceMemberId =
          flatWorkspaceMemberMaps.idByUserWorkspaceId[userWorkspaceId];

        return isDefined(workspaceMemberId)
          ? flatWorkspaceMemberMaps.byId[workspaceMemberId]
          : undefined;
      })
      .filter(isDefined);
  }

  private validateNotSelfAssignmentOrThrow({
    userWorkspaceIds,
    actingUserWorkspaceId,
  }: {
    userWorkspaceIds: string[];
    actingUserWorkspaceId?: string;
  }): void {
    if (
      isDefined(actingUserWorkspaceId) &&
      userWorkspaceIds.includes(actingUserWorkspaceId)
    ) {
      throw new PermissionsException(
        PermissionsExceptionMessage.CANNOT_UPDATE_SELF_ROLE,
        PermissionsExceptionCode.CANNOT_UPDATE_SELF_ROLE,
        {
          userFriendlyMessage: msg`You cannot change your own role. Please ask another administrator to update your role.`,
        },
      );
    }
  }

  private async getWorkspaceMemberByIdOrThrow({
    workspaceMemberId,
    workspaceId,
  }: {
    workspaceMemberId: string;
    workspaceId: string;
  }): Promise<WorkspaceMemberWorkspaceEntity> {
    const authContext = buildSystemAuthContext(workspaceId);

    return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
      const workspaceMemberRepository =
        this.workspaceOrmManager.getRepositoryWithoutPermissionChecks<WorkspaceMemberWorkspaceEntity>(
          'workspaceMember',
        );

      const workspaceMember = await workspaceMemberRepository.findOne({
        where: {
          id: workspaceMemberId,
        },
      });

      if (!isDefined(workspaceMember)) {
        throw new PermissionsException(
          'Workspace member not found',
          PermissionsExceptionCode.WORKSPACE_MEMBER_NOT_FOUND,
        );
      }

      return workspaceMember;
    }, authContext);
  }

  public async getUserWorkspaceIdsAssignedToRole(
    roleId: string,
    workspaceId: string,
  ): Promise<string[]> {
    const { userWorkspaceRoleMap } =
      await this.workspaceCacheService.getOrRecompute(workspaceId, [
        'userWorkspaceRoleMap',
      ]);

    return Object.entries(userWorkspaceRoleMap)
      .filter(([_, roleIdFromMap]) => roleIdFromMap === roleId)
      .map(([userWorkspaceId]) => userWorkspaceId);
  }

  public async validateUserWorkspaceIsNotUniqueAdminOrThrow({
    userWorkspaceId,
    workspaceId,
  }: {
    userWorkspaceId: string;
    workspaceId: string;
  }) {
    const roleOfUserWorkspace = await this.getRolesByUserWorkspaces({
      userWorkspaceIds: [userWorkspaceId],
      workspaceId,
    }).then((roles) => roles.get(userWorkspaceId)?.[0]);

    if (!isDefined(roleOfUserWorkspace)) {
      throw new PermissionsException(
        PermissionsExceptionMessage.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
        PermissionsExceptionCode.NO_ROLE_FOUND_FOR_USER_WORKSPACE,
        {
          userFriendlyMessage: msg`Your role in this workspace could not be found. Please contact your workspace administrator.`,
        },
      );
    }

    if (
      isDefined(roleOfUserWorkspace) &&
      roleOfUserWorkspace.universalIdentifier ===
        STANDARD_ROLE.admin.universalIdentifier
    ) {
      const adminRole = roleOfUserWorkspace;

      await this.validateMoreThanOneWorkspaceMemberHasAdminRoleOrThrow({
        adminRoleId: adminRole.id,
        workspaceId,
      });
    }
  }

  private async validateAssignRoleInputsAndGetUserWorkspaceIdsToAssign({
    userWorkspaceIds,
    workspaceId,
    roleId,
  }: {
    userWorkspaceIds: string[];
    workspaceId: string;
    roleId: string;
  }): Promise<string[]> {
    const userWorkspaces = await this.userWorkspaceRepository.find({
      where: {
        id: In(userWorkspaceIds),
      },
    });

    const foundUserWorkspaceIds = new Set(
      userWorkspaces.map((userWorkspace) => userWorkspace.id),
    );

    const missingUserWorkspaceIds = userWorkspaceIds.filter(
      (id) => !foundUserWorkspaceIds.has(id),
    );

    if (missingUserWorkspaceIds.length > 0) {
      throw new PermissionsException(
        `User workspaces not found: ${missingUserWorkspaceIds.join(', ')}`,
        PermissionsExceptionCode.USER_WORKSPACE_NOT_FOUND,
        {
          userFriendlyMessage: msg`Some workspace memberships could not be found. They may no longer have access to this workspace.`,
        },
      );
    }

    const rolesByUserWorkspaces = await this.getRolesByUserWorkspaces({
      userWorkspaceIds,
      workspaceId,
    });

    const userWorkspaceIdsToAssign: string[] = [];
    let adminRoleIdToValidate: string | undefined;

    for (const userWorkspaceId of userWorkspaceIds) {
      const currentRole = rolesByUserWorkspaces.get(userWorkspaceId)?.[0];

      if (currentRole?.id === roleId) {
        continue;
      }

      if (
        isDefined(currentRole) &&
        currentRole.universalIdentifier ===
          STANDARD_ROLE.admin.universalIdentifier
      ) {
        adminRoleIdToValidate = currentRole.id;
      }

      userWorkspaceIdsToAssign.push(userWorkspaceId);
    }

    if (isDefined(adminRoleIdToValidate)) {
      await this.validateMoreThanOneWorkspaceMemberHasAdminRoleOrThrow({
        workspaceId,
        adminRoleId: adminRoleIdToValidate,
      });
    }

    return userWorkspaceIdsToAssign;
  }

  private async validateMoreThanOneWorkspaceMemberHasAdminRoleOrThrow({
    adminRoleId,
    workspaceId,
  }: {
    adminRoleId: string;
    workspaceId: string;
  }) {
    const workspaceMembersWithAdminRole =
      await this.getWorkspaceMembersAssignedToRole(adminRoleId, workspaceId);

    if (workspaceMembersWithAdminRole.length === 1) {
      throw new PermissionsException(
        PermissionsExceptionMessage.CANNOT_UNASSIGN_LAST_ADMIN,
        PermissionsExceptionCode.CANNOT_UNASSIGN_LAST_ADMIN,
        {
          userFriendlyMessage: msg`You cannot remove the admin role from the last administrator. Please assign another administrator first.`,
        },
      );
    }
  }

  async resolveCustodianUserWorkspace({
    removedUserWorkspace,
    actingUserWorkspaceId,
  }: {
    removedUserWorkspace: UserWorkspaceEntity;
    actingUserWorkspaceId?: string;
  }): Promise<UserWorkspaceEntity | undefined> {
    const otherUserWorkspaces = await this.userWorkspaceRepository.find({
      where: {
        workspaceId: removedUserWorkspace.workspaceId,
        id: Not(removedUserWorkspace.id),
      },
      order: { createdAt: 'ASC' },
    });

    if (otherUserWorkspaces.length === 0) {
      return undefined;
    }

    const actingUserWorkspace = otherUserWorkspaces.find(
      (otherUserWorkspace) => otherUserWorkspace.id === actingUserWorkspaceId,
    );

    if (isDefined(actingUserWorkspace)) {
      return actingUserWorkspace;
    }

    const rolesByUserWorkspaceId = await this.getRolesByUserWorkspaces({
      userWorkspaceIds: otherUserWorkspaces.map(
        (otherUserWorkspace) => otherUserWorkspace.id,
      ),
      workspaceId: removedUserWorkspace.workspaceId,
    });

    const oldestAdminUserWorkspace = otherUserWorkspaces.find(
      (otherUserWorkspace) =>
        rolesByUserWorkspaceId
          .get(otherUserWorkspace.id)
          ?.some(
            (role) =>
              role.universalIdentifier ===
              STANDARD_ROLE.admin.universalIdentifier,
          ),
    );

    return oldestAdminUserWorkspace ?? otherUserWorkspaces[0];
  }
}