Skip to content

The open alternative to Salesforce, designed for AI.

6.1 KB
Raw Blame
import {
  Check,
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  type Relation,
  UpdateDateColumn,
} from 'typeorm';

import { type ConnectedAccountProvider } from 'twenty-shared/types';

import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ADD_ACCESS_TOKEN_EXPIRES_AT_TO_CONNECTED_ACCOUNT_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-54/add-access-token-expires-at-to-connected-account-upgrade-command-name.constant';
import { type EncryptedImapSmtpCaldavParams } from 'src/engine/core-modules/imap-smtp-caldav-connection/types/imap-smtp-caldav-connection.type';
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';

export type ConnectedAccountScope = 'USER' | 'WORKSPACE';

@Entity({ name: 'connectedAccount', schema: 'core' })
@Index('IDX_CONNECTED_ACCOUNT_CONNECTION_PROVIDER_ID', ['connectionProviderId'])
@Index('IDX_CONNECTED_ACCOUNT_APPLICATION_ID', ['applicationId'])
@Index('IDX_CONNECTED_ACCOUNT_HANDLE_PROVIDER', ['handle', 'provider'])
@Check(
  'CHK_connectedAccount_accessToken_encrypted',
  `"accessToken" IS NULL OR "accessToken" LIKE 'enc:v2:%'`,
)
@Check(
  'CHK_connectedAccount_refreshToken_encrypted',
  `"refreshToken" IS NULL OR "refreshToken" LIKE 'enc:v2:%'`,
)
@Check(
  'CHK_connectedAccount_connectionParameters_encrypted',
  `"connectionParameters" IS NULL OR (` +
    `(("connectionParameters"->'IMAP'->>'password') IS NULL OR ("connectionParameters"->'IMAP'->>'password') LIKE 'enc:v2:%') ` +
    `AND (("connectionParameters"->'SMTP'->>'password') IS NULL OR ("connectionParameters"->'SMTP'->>'password') LIKE 'enc:v2:%') ` +
    `AND (("connectionParameters"->'CALDAV'->>'password') IS NULL OR ("connectionParameters"->'CALDAV'->>'password') LIKE 'enc:v2:%')` +
    `)`,
)
export class ConnectedAccountEntity extends WorkspaceRelatedEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', nullable: false })
  handle: string;

  @Column({
    type: 'varchar',
    length: EXTERNAL_ACCOUNT_ID_MAX_LENGTH,
    nullable: true,
  })
  @WasIntroducedInUpgrade({
    upgradeCommandName:
      '2.48.0_AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand_1791975194413',
  })
  externalAccountId: string | null;

  @Column({ type: 'varchar', nullable: false })
  provider: ConnectedAccountProvider;

  @Column({ type: 'varchar', nullable: true })
  accessToken: EncryptedString | null;

  @Column({ type: 'varchar', nullable: true })
  refreshToken: EncryptedString | null;

  @Column({ type: 'timestamptz', nullable: true })
  lastCredentialsRefreshedAt: Date | null;

  @Column({ type: 'timestamptz', nullable: true })
  @WasIntroducedInUpgrade({
    upgradeCommandName:
      ADD_ACCESS_TOKEN_EXPIRES_AT_TO_CONNECTED_ACCOUNT_UPGRADE_COMMAND_NAME,
  })
  accessTokenExpiresAt: Date | null;

  @Column({ type: 'timestamptz', nullable: true })
  authFailedAt: Date | null;

  @Column({ type: 'varchar', nullable: true })
  @WasIntroducedInUpgrade({
    upgradeCommandName:
      '2.40.0_AddAuthFailedReasonToConnectedAccountFastInstanceCommand_1788781233982',
  })
  authFailedReason: string | null;

  @Column({ type: 'timestamptz', nullable: true })
  archivedAt: Date | null;

  @Column({ type: 'varchar', array: true, nullable: true })
  handleAliases: string[] | null;

  @Column({ type: 'varchar', array: true, nullable: true })
  scopes: string[] | null;

  @Column({ type: 'jsonb', nullable: true })
  connectionParameters: EncryptedImapSmtpCaldavParams | null;

  @Column({ type: 'timestamptz', nullable: true })
  lastSignedInAt: Date | null;

  @Column({ type: 'jsonb', nullable: true })
  oidcTokenClaims: Record<string, unknown> | null;

  @Column({ type: 'uuid', nullable: false })
  userWorkspaceId: string;

  @Column({ type: 'uuid', nullable: true })
  connectionProviderId: string | null;

  @ManyToOne(() => ConnectionProviderEntity, {
    onDelete: 'CASCADE',
    nullable: true,
  })
  @JoinColumn({ name: 'connectionProviderId' })
  connectionProvider: Relation<ConnectionProviderEntity> | null;

  @Column({ type: 'uuid', nullable: true })
  applicationId: string | null;

  @ManyToOne(() => ApplicationEntity, {
    onDelete: 'CASCADE',
    nullable: true,
  })
  @JoinColumn({ name: 'applicationId' })
  application: Relation<ApplicationEntity> | null;

  @Column({ type: 'varchar', nullable: true })
  name: string | null;

  @Column({ type: 'varchar', nullable: false, default: 'USER' })
  @WasIntroducedInUpgrade({
    upgradeCommandName:
      '2.49.0_AddConnectedAccountScopeFastInstanceCommand_1792170228100',
  })
  scope: ConnectedAccountScope;

  // TODO: drop with the sync trigger next release; only previous-release servers use it
  @Column({
    type: 'varchar',
    nullable: false,
    select: false,
    insert: false,
    update: false,
  })
  visibility: 'user' | 'workspace';

  @OneToMany(
    'MessageChannelEntity',
    (messageChannel: MessageChannelEntity) => messageChannel.connectedAccount,
  )
  messageChannels: Relation<MessageChannelEntity[]>;

  @OneToMany(
    'CalendarChannelEntity',
    (calendarChannel: CalendarChannelEntity) =>
      calendarChannel.connectedAccount,
  )
  calendarChannels: Relation<CalendarChannelEntity[]>;

  @CreateDateColumn({ type: 'timestamptz' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamptz' })
  updatedAt: Date;
}