From 712e05c3553e90bca8abd7b248e307216e23b544 Mon Sep 17 00:00:00 2001 From: "Rahul R." Date: Fri, 24 Jan 2025 12:47:45 +0530 Subject: [PATCH 1/4] fix: added few constants and utils --- packages/common/package.json | 1 + packages/common/src/index.ts | 1 - packages/common/src/lib/constants.ts | 12 -- .../lib/decorators/feature-flag.decorator.ts | 2 +- .../src/lib/decorators/public.decorator.ts | 4 +- .../lib/guards/feature-flag-enabled.guard.ts | 23 +-- packages/config/package.json | 2 + .../config/src/lib/default-configuration.ts | 10 +- packages/constants/src/index.ts | 7 +- packages/constants/src/lib/ai.ts | 4 + packages/constants/src/lib/api.ts | 7 + packages/constants/src/lib/code.ts | 10 + packages/constants/src/lib/github.ts | 12 ++ .../constants/src/lib/reflect-metadata.ts | 7 + packages/contracts/src/lib/github.model.ts | 182 +++++++++--------- packages/core/src/lib/auth/auth.service.ts | 12 +- .../lib/auth/email-confirmation.service.ts | 8 +- packages/core/src/lib/constants.ts | 5 - packages/core/src/lib/core/utils.ts | 37 +--- packages/core/src/lib/dev-config.ts | 13 +- .../lib/email-reset/email-reset.service.ts | 5 +- ...email-template.generate-preview.handler.ts | 25 +-- .../core/src/lib/invite/invite.service.ts | 17 +- .../dto/validate-join-request.dto.ts | 41 ++-- .../organization-team-join-request.service.ts | 11 +- .../decorators/permissions.decorator.ts | 2 +- .../lib/shared/decorators/roles.decorator.ts | 2 +- .../core/src/lib/shared/guards/auth.guard.ts | 2 +- .../lib/shared/guards/feature-flag.guard.ts | 2 +- .../guards/organization-permission.guard.ts | 2 +- .../src/lib/shared/guards/permission.guard.ts | 2 +- .../core/src/lib/shared/guards/role.guard.ts | 2 +- .../shared/guards/tenant-permission.guard.ts | 2 +- packages/core/src/lib/stats/stats.guard.ts | 2 +- .../core/src/lib/user/dto/user-code.dto.ts | 19 +- packages/plugin/src/lib/constants.ts | 4 - packages/plugin/src/lib/plugin-metadata.ts | 24 ++- packages/plugin/src/lib/plugin.ts | 4 +- .../integration-ai/src/lib/constants.ts | 1 - .../integration-ai/src/lib/gauzy-ai.module.ts | 6 +- .../src/lib/request-config.provider.ts | 4 +- .../src/lib/components/view/view.component.ts | 6 +- .../src/lib/github/github-sync.service.ts | 5 +- .../project-mutation.component.ts | 8 +- packages/utils/package.json | 1 + packages/utils/src/index.ts | 2 + packages/utils/src/lib/array-to-object.ts | 30 +++ packages/utils/src/lib/code-generator.ts | 19 ++ 48 files changed, 319 insertions(+), 290 deletions(-) delete mode 100644 packages/common/src/lib/constants.ts create mode 100644 packages/constants/src/lib/ai.ts create mode 100644 packages/constants/src/lib/api.ts create mode 100644 packages/constants/src/lib/code.ts create mode 100644 packages/constants/src/lib/github.ts create mode 100644 packages/constants/src/lib/reflect-metadata.ts delete mode 100644 packages/core/src/lib/constants.ts delete mode 100644 packages/plugin/src/lib/constants.ts delete mode 100644 packages/plugins/integration-ai/src/lib/constants.ts create mode 100644 packages/utils/src/lib/array-to-object.ts create mode 100644 packages/utils/src/lib/code-generator.ts diff --git a/packages/common/package.json b/packages/common/package.json index 92f3ca7efcb..5be258ba2be 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@apollo/server": "^4.11.3", + "@gauzy/constants": "^0.1.0", "@gauzy/contracts": "^0.1.0", "@mikro-orm/nestjs": "^6.0.2", "@nestjs/common": "^10.4.15", diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts index 7f9ee4423c2..37a04c17555 100644 --- a/packages/common/src/index.ts +++ b/packages/common/src/index.ts @@ -1,7 +1,6 @@ /** * Public API Surface of @gauzy/common */ -export * from './lib/constants'; export * from './lib/decorators'; export * from './lib/enums'; export * from './lib/guards'; diff --git a/packages/common/src/lib/constants.ts b/packages/common/src/lib/constants.ts deleted file mode 100644 index fca8cc997f2..00000000000 --- a/packages/common/src/lib/constants.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Constants which are shared between all packages - */ -export const DEFAULT_API_PORT = 3000; -export const DEFAULT_API_HOST = '127.0.0.1'; -export const DEFAULT_API_BASE_URL = 'http://127.0.0.1:3000'; -export const DEFAULT_GRAPHQL_API_PATH = 'graphql'; - -export const PUBLIC_METHOD_METADATA = '__public:route__'; -export const ROLES_METADATA = 'roles'; -export const PERMISSIONS_METADATA = 'permissions'; -export const FEATURE_METADATA = 'feature'; \ No newline at end of file diff --git a/packages/common/src/lib/decorators/feature-flag.decorator.ts b/packages/common/src/lib/decorators/feature-flag.decorator.ts index 3f2f7afe3c3..43dbba1b4b2 100644 --- a/packages/common/src/lib/decorators/feature-flag.decorator.ts +++ b/packages/common/src/lib/decorators/feature-flag.decorator.ts @@ -1,5 +1,5 @@ import { SetMetadata } from '@nestjs/common'; +import { FEATURE_METADATA } from '@gauzy/constants'; import { FeatureEnum } from '@gauzy/contracts'; -import { FEATURE_METADATA } from './../constants'; export const FeatureFlag = (feature: FeatureEnum) => SetMetadata(FEATURE_METADATA, feature); diff --git a/packages/common/src/lib/decorators/public.decorator.ts b/packages/common/src/lib/decorators/public.decorator.ts index 75e903463ba..77e50b4f6af 100644 --- a/packages/common/src/lib/decorators/public.decorator.ts +++ b/packages/common/src/lib/decorators/public.decorator.ts @@ -1,5 +1,5 @@ import { CustomDecorator, SetMetadata } from '@nestjs/common'; -import { PUBLIC_METHOD_METADATA } from './../constants'; +import { PUBLIC_METHOD_METADATA } from '@gauzy/constants'; /** * Decorator that assigns metadata to the class/function using the @@ -12,4 +12,4 @@ import { PUBLIC_METHOD_METADATA } from './../constants'; * * @publicApi */ -export const Public = (): CustomDecorator => SetMetadata(PUBLIC_METHOD_METADATA, true); \ No newline at end of file +export const Public = (): CustomDecorator => SetMetadata(PUBLIC_METHOD_METADATA, true); diff --git a/packages/common/src/lib/guards/feature-flag-enabled.guard.ts b/packages/common/src/lib/guards/feature-flag-enabled.guard.ts index 65f7b951fc4..deb232d080d 100644 --- a/packages/common/src/lib/guards/feature-flag-enabled.guard.ts +++ b/packages/common/src/lib/guards/feature-flag-enabled.guard.ts @@ -1,12 +1,7 @@ -import { - CanActivate, - ExecutionContext, - Injectable, - NotFoundException, -} from '@nestjs/common'; +import { CanActivate, ExecutionContext, Injectable, NotFoundException } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; +import { FEATURE_METADATA } from '@gauzy/constants'; import { FeatureEnum, IAuthenticationFlagFeatures } from '@gauzy/contracts'; -import { FEATURE_METADATA } from '../constants'; /** * Check if a specific feature is enabled based on the environment variable. @@ -15,7 +10,7 @@ import { FEATURE_METADATA } from '../constants'; * @returns True if the feature is enabled, otherwise false. */ const featureEnabled = (feature: Extract) => { - return process.env[feature] !== 'false'; + return process.env[feature] !== 'false'; }; /** @@ -44,7 +39,7 @@ export const flagFeatures: IAuthenticationFlagFeatures = { FEATURE_MICROSOFT_LOGIN: featureEnabled(FeatureEnum.FEATURE_MICROSOFT_LOGIN), /** Flag indicating whether LinkedIn login is enabled. */ - FEATURE_LINKEDIN_LOGIN: featureEnabled(FeatureEnum.FEATURE_LINKEDIN_LOGIN), + FEATURE_LINKEDIN_LOGIN: featureEnabled(FeatureEnum.FEATURE_LINKEDIN_LOGIN) }; /** @@ -63,19 +58,19 @@ export class FeatureFlagEnabledGuard implements CanActivate { */ async canActivate(context: ExecutionContext) { /* - * Retrieve metadata for a specified key for a specified set of features - */ + * Retrieve metadata for a specified key for a specified set of features + */ const flag = this._reflector.getAllAndOverride(FEATURE_METADATA, [ context.getHandler(), // Returns a reference to the handler (method) that will be invoked next in the request pipeline. - context.getClass(), // Returns the *type* of the controller class which the current handler belongs to. + context.getClass() // Returns the *type* of the controller class which the current handler belongs to. ]); if (!!flagFeatures[flag]) { return true; } /** - * If the feature is not enabled, throw a NotFoundException. - */ + * If the feature is not enabled, throw a NotFoundException. + */ const httpContext = context.switchToHttp(); const request = httpContext.getRequest(); throw new NotFoundException(`Cannot ${request.method} ${request.url}`); diff --git a/packages/config/package.json b/packages/config/package.json index 757fef1bc31..4c5ad71a9d6 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -27,6 +27,8 @@ "lib:watch": "yarn nx build config --watch" }, "dependencies": { + "@gauzy/constants": "^0.1.0", + "@gauzy/common": "^0.1.0", "@gauzy/contracts": "^0.1.0", "@gauzy/utils": "^0.1.0", "@mikro-orm/better-sqlite": "^6.4.2", diff --git a/packages/config/src/lib/default-configuration.ts b/packages/config/src/lib/default-configuration.ts index d2b920e1e49..b5c682bd6ec 100644 --- a/packages/config/src/lib/default-configuration.ts +++ b/packages/config/src/lib/default-configuration.ts @@ -2,13 +2,9 @@ import * as dotenv from 'dotenv'; dotenv.config(); import * as path from 'path'; -import { - DEFAULT_API_HOST, - DEFAULT_API_PORT, - DEFAULT_API_BASE_URL, - DEFAULT_GRAPHQL_API_PATH, - ApplicationPluginConfig -} from '@gauzy/common'; +import { ApplicationPluginConfig } from '@gauzy/common'; +import { DEFAULT_API_HOST, DEFAULT_API_PORT, DEFAULT_API_BASE_URL, DEFAULT_GRAPHQL_API_PATH } from '@gauzy/constants'; +import {} from '@gauzy/contracts'; import { dbTypeOrmConnectionConfig, dbMikroOrmConnectionConfig, dbKnexConnectionConfig } from './database'; process.cwd(); diff --git a/packages/constants/src/index.ts b/packages/constants/src/index.ts index 98dc44b799f..c88cff7564d 100644 --- a/packages/constants/src/index.ts +++ b/packages/constants/src/index.ts @@ -1,2 +1,7 @@ -export * from './lib/task'; +export * from './lib/ai'; +export * from './lib/api'; +export * from './lib/code'; +export * from './lib/github'; +export * from './lib/reflect-metadata'; export * from './lib/organization'; +export * from './lib/task'; diff --git a/packages/constants/src/lib/ai.ts b/packages/constants/src/lib/ai.ts new file mode 100644 index 00000000000..eb96396c134 --- /dev/null +++ b/packages/constants/src/lib/ai.ts @@ -0,0 +1,4 @@ +/** + * Injection token for Gauzy AI configuration. + */ +export const GAUZY_AI_CONFIG_TOKEN = 'GAUZY_AI_CONFIG_TOKEN'; diff --git a/packages/constants/src/lib/api.ts b/packages/constants/src/lib/api.ts new file mode 100644 index 00000000000..9aee01b89e3 --- /dev/null +++ b/packages/constants/src/lib/api.ts @@ -0,0 +1,7 @@ +/** + * API-related default constants used across all packages. + */ +export const DEFAULT_API_PORT = 3000; +export const DEFAULT_API_HOST = '127.0.0.1'; +export const DEFAULT_API_BASE_URL = `http://${DEFAULT_API_HOST}:${DEFAULT_API_PORT}`; +export const DEFAULT_GRAPHQL_API_PATH = 'graphql'; diff --git a/packages/constants/src/lib/code.ts b/packages/constants/src/lib/code.ts new file mode 100644 index 00000000000..9b6c8bab4b1 --- /dev/null +++ b/packages/constants/src/lib/code.ts @@ -0,0 +1,10 @@ +/** + * Represents the default length of generated alphanumeric codes. + */ +export const ALPHA_NUMERIC_CODE_LENGTH = 6; + +/** + * Represents a demo or magic code that allows authentication without a password. + * Typically used for demo environments or special login scenarios. + */ +export const DEMO_PASSWORD_LESS_MAGIC_CODE = '123456'; diff --git a/packages/constants/src/lib/github.ts b/packages/constants/src/lib/github.ts new file mode 100644 index 00000000000..3b72fedd514 --- /dev/null +++ b/packages/constants/src/lib/github.ts @@ -0,0 +1,12 @@ +/** + * Sync tag constants used to categorize synchronization sources. + */ +export const SyncTags = { + GITHUB: 'GitHub', + GAUZY: 'Gauzy' +} as const; + +/** + * Type definition for valid sync tag values. + */ +export type SyncTag = (typeof SyncTags)[keyof typeof SyncTags]; diff --git a/packages/constants/src/lib/reflect-metadata.ts b/packages/constants/src/lib/reflect-metadata.ts new file mode 100644 index 00000000000..ae5e146df3b --- /dev/null +++ b/packages/constants/src/lib/reflect-metadata.ts @@ -0,0 +1,7 @@ +/** + * Metadata keys used for decorators and security features. + */ +export const PUBLIC_METHOD_METADATA = '__public:route__'; +export const ROLES_METADATA = '__roles__'; +export const PERMISSIONS_METADATA = '__permissions__'; +export const FEATURE_METADATA = '__feature__'; diff --git a/packages/contracts/src/lib/github.model.ts b/packages/contracts/src/lib/github.model.ts index 916f3f42629..c262292b5b1 100644 --- a/packages/contracts/src/lib/github.model.ts +++ b/packages/contracts/src/lib/github.model.ts @@ -1,164 +1,166 @@ import { IIntegrationTenant, IRelationalIntegrationTenant } from './integration.model'; -import { IBasePerTenantAndOrganizationEntityModel } from './base-entity.model'; +import { IBasePerTenantAndOrganizationEntityModel, ID } from './base-entity.model'; import { IRelationalOrganizationProject } from './organization-projects.model'; -export const SYNC_TAG_GITHUB = 'GitHub'; -export const SYNC_TAG_GAUZY = 'Gauzy'; - // Common input properties for GitHub app installation and OAuth app installation interface IGithubAppInstallInputCommon extends IBasePerTenantAndOrganizationEntityModel { - provider?: string; + provider?: string; } // Input properties for GitHub app installation export interface IGithubAppInstallInput extends IGithubAppInstallInputCommon { - installation_id?: string; - setup_action?: string; - state?: string; + installation_id?: string; + setup_action?: string; + state?: string; } // Input properties for OAuth app installation export interface IOAuthAppInstallInput extends IGithubAppInstallInputCommon { - code?: string; + code?: string; } - // Represents a GitHub repository export interface IGithubRepository { - id: number; - node_id: string; - name: string; - full_name: string; - private: boolean; - visibility: string; - open_issues_count: number; - owner?: { - id: number; - login: string; - node_id: string; - } - [x: string]: any; // Additional properties + id: number; + node_id: string; + name: string; + full_name: string; + private: boolean; + visibility: string; + open_issues_count: number; + owner?: { + id: number; + login: string; + node_id: string; + }; + [x: string]: any; // Additional properties } export interface IGithubIssueFindInput extends IBasePerTenantAndOrganizationEntityModel { - page: number; - per_page: number; + page: number; + per_page: number; } // Represents a GitHub issue export interface IGithubIssue { - id: number; - node_id: string; - number: number; - title: string; - state: string; - body: string; - labels: IGithubIssueLabel[]; - [x: string]: any; // Additional properties + id: number; + node_id: string; + number: number; + title: string; + state: string; + body: string; + labels: IGithubIssueLabel[]; + [x: string]: any; // Additional properties } // Represents a GitHub issue label export interface IGithubIssueLabel { - id: number; - node_id: string; - url: string; - name: string; - color: string; - default: boolean; - description: string; - [x: string]: any; // Additional properties + id: number; + node_id: string; + url: string; + name: string; + color: string; + default: boolean; + description: string; + [x: string]: any; // Additional properties } export interface IGithubIssueCreateOrUpdatePayload { - repo: string; - owner: string; - issue_number?: number; - title: string; - body: string; - labels: Partial; + repo: string; + owner: string; + issue_number?: number; + title: string; + body: string; + labels: Partial; } // Represents a GitHub installation export interface IGithubInstallation { - id: number; - node_id: string; + id: number; + node_id: string; } // Response containing GitHub repositories export interface IGithubRepositoryResponse { - total_count: number; - repository_selection: string; - repositories: IGithubRepository[]; + total_count: number; + repository_selection: string; + repositories: IGithubRepository[]; } // Enum for GitHub property mapping export enum GithubPropertyMapEnum { - INSTALLATION_ID = 'installation_id', - SETUP_ACTION = 'setup_action', - ACCESS_TOKEN = 'access_token', - EXPIRES_IN = 'expires_in', - REFRESH_TOKEN = 'refresh_token', - REFRESH_TOKEN_EXPIRES_IN = 'refresh_token_expires_in', - TOKEN_TYPE = 'token_type', - SYNC_TAG = 'sync_tag' + INSTALLATION_ID = 'installation_id', + SETUP_ACTION = 'setup_action', + ACCESS_TOKEN = 'access_token', + EXPIRES_IN = 'expires_in', + REFRESH_TOKEN = 'refresh_token', + REFRESH_TOKEN_EXPIRES_IN = 'refresh_token_expires_in', + TOKEN_TYPE = 'token_type', + SYNC_TAG = 'sync_tag' } -export interface IGithubSyncIssuePayload extends IBasePerTenantAndOrganizationEntityModel, IRelationalOrganizationProject { - issues: IGithubIssue | IGithubIssue[]; - repository: IOrganizationGithubRepository; +export interface IGithubSyncIssuePayload + extends IBasePerTenantAndOrganizationEntityModel, + IRelationalOrganizationProject { + issues: IGithubIssue | IGithubIssue[]; + repository: IOrganizationGithubRepository; } /** * Represents a payload for GitHub issues, including organization and tenant information. */ export interface IGithubRepositoryPayload { - repository: IGithubRepository; + repository: IGithubRepository; } /** */ export interface IGithubAutomationBase extends IGithubRepositoryPayload { - integration: IIntegrationTenant; + integration: IIntegrationTenant; } export interface IGithubAutomationIssuePayload extends IGithubAutomationBase { - issue: IGithubIssue; + issue: IGithubIssue; } export interface IGithubInstallationDeletedPayload extends Pick { - installation: IGithubInstallation; - repositories: IGithubRepository[]; + installation: IGithubInstallation; + repositories: IGithubRepository[]; } -export interface IOrganizationGithubRepository extends IBasePerTenantAndOrganizationEntityModel, IRelationalIntegrationTenant { - repositoryId: number; - name: string; - fullName: string; - owner: string; - issuesCount: number; - hasSyncEnabled: boolean; - private: boolean; - status: string; +export interface IOrganizationGithubRepository + extends IBasePerTenantAndOrganizationEntityModel, + IRelationalIntegrationTenant { + repositoryId: number; + name: string; + fullName: string; + owner: string; + issuesCount: number; + hasSyncEnabled: boolean; + private: boolean; + status: string; } -export interface IOrganizationGithubRepositoryUpdateInput extends Partial { } +export interface IOrganizationGithubRepositoryUpdateInput extends Partial {} -export interface IOrganizationGithubRepositoryFindInput extends Partial { } +export interface IOrganizationGithubRepositoryFindInput extends Partial {} export interface IOrganizationGithubRepositoryIssue extends IBasePerTenantAndOrganizationEntityModel { - issueId: number; - issueNumber: number; - /** Issue Sync With Repository */ - repository?: IOrganizationGithubRepository; - repositoryId?: IOrganizationGithubRepository['id']; + issueId: number; + issueNumber: number; + /** Issue Sync With Repository */ + repository?: IOrganizationGithubRepository; + repositoryId?: ID; } -export interface IIntegrationMapSyncRepository extends IBasePerTenantAndOrganizationEntityModel, IRelationalIntegrationTenant { - repository: IGithubRepository; +export interface IIntegrationMapSyncRepository + extends IBasePerTenantAndOrganizationEntityModel, + IRelationalIntegrationTenant { + repository: IGithubRepository; } export enum GithubRepositoryStatusEnum { - SYNCING = 'Syncing', - SUCCESSFULLY = 'Successfully', - ERROR = 'Error', - DISABLED = 'Disabled', + SYNCING = 'Syncing', + SUCCESSFULLY = 'Successfully', + ERROR = 'Error', + DISABLED = 'Disabled' } diff --git a/packages/core/src/lib/auth/auth.service.ts b/packages/core/src/lib/auth/auth.service.ts index 795cc13d0ef..171c44a6feb 100644 --- a/packages/core/src/lib/auth/auth.service.ts +++ b/packages/core/src/lib/auth/auth.service.ts @@ -14,6 +14,7 @@ import { JsonWebTokenError, JwtPayload, sign, verify } from 'jsonwebtoken'; import { pick } from 'underscore'; import { IAppIntegrationConfig } from '@gauzy/common'; import { environment } from '@gauzy/config'; +import { DEMO_PASSWORD_LESS_MAGIC_CODE } from '@gauzy/constants'; import { IUserRegistrationInput, LanguagesEnum, @@ -42,10 +43,9 @@ import { ID } from '@gauzy/contracts'; import { SocialAuthService } from '@gauzy/auth'; -import { buildQueryString, deepMerge, isNotEmpty } from '@gauzy/utils'; +import { buildQueryString, deepMerge, generateAlphaNumericCode, isNotEmpty } from '@gauzy/utils'; import { AccountRegistrationEvent } from '../event-bus/events'; import { EventBus } from '../event-bus/event-bus'; -import { ALPHA_NUMERIC_CODE_LENGTH, DEMO_PASSWORD_LESS_MAGIC_CODE } from './../constants'; import { EmailService } from './../email-send/email.service'; import { UserService } from '../user/user.service'; import { EmployeeService } from '../employee/employee.service'; @@ -54,7 +54,7 @@ import { UserOrganizationService } from '../user-organization/user-organization. import { ImportRecordUpdateOrCreateCommand } from './../export-import/import-record'; import { PasswordResetCreateCommand, PasswordResetGetCommand } from './../password-reset/commands'; import { RequestContext } from './../core/context'; -import { freshTimestamp, generateRandomAlphaNumericCode } from './../core/utils'; +import { freshTimestamp } from './../core/utils'; import { OrganizationTeam, Tenant, User } from './../core/entities/internal'; import { EmailConfirmationService } from './email-confirmation.service'; import { prepareSQLQuery as p } from './../database/database.helper'; @@ -181,7 +181,7 @@ export class AuthService extends SocialAuthService { throw new UnauthorizedException(); } - const code = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + const code = generateAlphaNumericCode(); const codeExpireAt = moment().add(environment.MAGIC_CODE_EXPIRATION_TIME, 'seconds').toDate(); // Update all users with a single query @@ -306,7 +306,7 @@ export class AuthService extends SocialAuthService { ); } - const code = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + const code = generateAlphaNumericCode(); const codeExpireAt = moment().add(environment.MAGIC_CODE_EXPIRATION_TIME, 'seconds').toDate(); // Update all users with a single query @@ -955,7 +955,7 @@ export class AuthService extends SocialAuthService { } if (!isDemoCode) { - magicCode = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + magicCode = generateAlphaNumericCode(); } // Calculate the expiration time for the code diff --git a/packages/core/src/lib/auth/email-confirmation.service.ts b/packages/core/src/lib/auth/email-confirmation.service.ts index ac748a6568b..09b723a9746 100644 --- a/packages/core/src/lib/auth/email-confirmation.service.ts +++ b/packages/core/src/lib/auth/email-confirmation.service.ts @@ -5,7 +5,6 @@ import { JwtPayload, sign, verify } from 'jsonwebtoken'; import * as bcrypt from 'bcrypt'; import * as moment from 'moment'; import { IAppIntegrationConfig } from '@gauzy/common'; -import { deepMerge } from '@gauzy/utils'; import { FeatureEnum, IBasePerTenantEntityModel, @@ -15,12 +14,11 @@ import { IUserTokenInput, IVerificationTokenPayload } from '@gauzy/contracts'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../constants'; +import { deepMerge, generateAlphaNumericCode } from '@gauzy/utils'; +import { RequestContext } from './../core/context/request-context'; import { EmailService } from './../email-send/email.service'; import { UserService } from './../user/user.service'; import { FeatureService } from './../feature/feature.service'; -import { RequestContext } from './../core/context'; -import { generateRandomAlphaNumericCode } from './../core/utils'; @Injectable() export class EmailConfirmationService { @@ -54,7 +52,7 @@ export class EmailConfirmationService { const appIntegration = deepMerge(environment.appIntegrationConfig, integration); const verificationLink = `${appIntegration.appEmailConfirmationUrl}?email=${email}&token=${token}`; - const verificationCode = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + const verificationCode = generateAlphaNumericCode(); // Update user's email token field and verification code await this.userService.update(id, { diff --git a/packages/core/src/lib/constants.ts b/packages/core/src/lib/constants.ts deleted file mode 100644 index 07d64d9f5b5..00000000000 --- a/packages/core/src/lib/constants.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Represents the length of alpha-numeric codes. -export const ALPHA_NUMERIC_CODE_LENGTH = 6; - -// Represents a demo or magic code without an associated password. -export const DEMO_PASSWORD_LESS_MAGIC_CODE = '123456'; diff --git a/packages/core/src/lib/core/utils.ts b/packages/core/src/lib/core/utils.ts index 0cdc0641199..970fe0189b0 100644 --- a/packages/core/src/lib/core/utils.ts +++ b/packages/core/src/lib/core/utils.ts @@ -15,11 +15,11 @@ import { sample } from 'underscore'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; +import { ALPHA_NUMERIC_CODE_LENGTH } from '@gauzy/constants'; import { DateRange, IDateRange, IUser } from '@gauzy/contracts'; import { IDBConnectionOptions } from '@gauzy/common'; import { getConfig, DatabaseTypeEnum } from '@gauzy/config'; import { moment } from './../core/moment-extend'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../constants'; namespace Utils { export function generatedLogoColor() { @@ -56,15 +56,6 @@ export function getLastDayOfMonth(year, month) { return new Date(year, month + 1, 0).getDate(); } -export function arrayToObject(array, key, value) { - return array.reduce((prev, current) => { - return { - ...prev, - [current[key]]: current[value] - }; - }, {}); -} - /* * To convert unix timestamp to datetime using date format */ @@ -269,32 +260,6 @@ export function getDaysBetweenDates( return Array.from(ranges.by('day')).map((date: moment.Moment) => date.format('YYYY-MM-DD')); } -/** - * Generating a random integer number with flexible length - * - * @param length - */ -export function generateRandomInteger(length = 6) { - return Math.floor(Math.pow(10, length - 1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1)); -} - -/** - * Generate a random alphanumeric code. - * @param length The length of the code. Default is 6. - * @returns The generated code. - */ -export function generateRandomAlphaNumericCode(length: number = ALPHA_NUMERIC_CODE_LENGTH): string { - const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - let code = ''; - - for (let i = 0; i < length; i++) { - const index = Math.floor(Math.random() * characters.length); - code += characters[index]; - } - - return code; -} - /** * Get a fresh timestamp for the entity. * diff --git a/packages/core/src/lib/dev-config.ts b/packages/core/src/lib/dev-config.ts index 42a43d871db..b3fa355547a 100644 --- a/packages/core/src/lib/dev-config.ts +++ b/packages/core/src/lib/dev-config.ts @@ -1,13 +1,10 @@ -import { - DEFAULT_API_BASE_URL, - DEFAULT_API_HOST, - DEFAULT_API_PORT, - DEFAULT_GRAPHQL_API_PATH, - ApplicationPluginConfig -} from '@gauzy/common'; +import { ApplicationPluginConfig } from '@gauzy/common'; +import { DEFAULT_API_BASE_URL, DEFAULT_API_HOST, DEFAULT_API_PORT, DEFAULT_GRAPHQL_API_PATH } from '@gauzy/constants'; import { dbTypeOrmConnectionConfig, dbMikroOrmConnectionConfig, dbKnexConnectionConfig } from '@gauzy/config'; -// Define the dev configuration +/** + * Application plugin configuration for development environment. + */ export const devConfig: ApplicationPluginConfig = { apiConfigOptions: { host: process.env.API_HOST || DEFAULT_API_HOST, diff --git a/packages/core/src/lib/email-reset/email-reset.service.ts b/packages/core/src/lib/email-reset/email-reset.service.ts index 5b5f85b3f6e..18d97530b07 100644 --- a/packages/core/src/lib/email-reset/email-reset.service.ts +++ b/packages/core/src/lib/email-reset/email-reset.service.ts @@ -2,13 +2,12 @@ import { CommandBus, QueryBus } from '@nestjs/cqrs'; import { HttpStatus, Injectable, NotFoundException } from '@nestjs/common'; import { IsNull, MoreThanOrEqual, SelectQueryBuilder } from 'typeorm'; import { IEmailReset, IEmailResetFindInput, LanguagesEnum } from '@gauzy/contracts'; +import { generateAlphaNumericCode } from '@gauzy/utils'; import { RequestContext } from '../core/context'; import { UserService } from '../user/user.service'; import { TenantAwareCrudService } from '../core/crud'; import { EmailReset } from './email-reset.entity'; import { UserEmailDTO } from '../user/dto'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../constants'; -import { generateRandomAlphaNumericCode } from './../core/utils'; import { EmailResetCreateCommand } from './commands'; import { EmailResetGetQuery } from './queries'; import { VerifyEmailResetRequestDTO } from './dto/verify-email-reset-request.dto'; @@ -54,7 +53,7 @@ export class EmailResetService extends TenantAwareCrudService { }); } - const verificationCode = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + const verificationCode = generateAlphaNumericCode(); await this.commandBus.execute( new EmailResetCreateCommand({ diff --git a/packages/core/src/lib/email-template/queries/handlers/email-template.generate-preview.handler.ts b/packages/core/src/lib/email-template/queries/handlers/email-template.generate-preview.handler.ts index 7bc05fb4d36..847cf0396a5 100644 --- a/packages/core/src/lib/email-template/queries/handlers/email-template.generate-preview.handler.ts +++ b/packages/core/src/lib/email-template/queries/handlers/email-template.generate-preview.handler.ts @@ -2,22 +2,15 @@ import { IQueryHandler, QueryHandler } from '@nestjs/cqrs'; import * as Handlebars from 'handlebars'; import * as mjml2html from 'mjml'; import { ConfigService, environment } from '@gauzy/config'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../../../constants'; +import { generateAlphaNumericCode } from '@gauzy/utils'; import { EmailTemplateGeneratePreviewQuery } from '../email-template.generate-preview.query'; import { moment } from '../../../core/moment-extend'; -import { generateRandomAlphaNumericCode } from './../../../core/utils'; @QueryHandler(EmailTemplateGeneratePreviewQuery) -export class EmailTemplateGeneratePreviewHandler - implements IQueryHandler { +export class EmailTemplateGeneratePreviewHandler implements IQueryHandler { + constructor(private readonly configService: ConfigService) {} - constructor( - private readonly configService: ConfigService - ) { } - - public async execute( - command: EmailTemplateGeneratePreviewQuery - ): Promise<{ html: string }> { + public async execute(command: EmailTemplateGeneratePreviewQuery): Promise<{ html: string }> { const { input } = command; let textToHtml = input; @@ -80,18 +73,18 @@ export class EmailTemplateGeneratePreviewHandler task_update_project: 'Gauzy Project', task_update_assign_by: 'Ruslan Konviser', task_update_url: 'https://github.com/ever-co/ever-gauzy/issues/1688', - inviteCode: generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH), + inviteCode: generateAlphaNumericCode(), teams: 'Gauzy Team', - verificationCode: generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH), + verificationCode: generateAlphaNumericCode(), appName: appName, appLogo: appLogo, appSignature: appSignature, appLink: appLink, items: [ { - tenantName: "Default", - userName: "Default", - resetLink: "https://github.com/ever-co/ever-gauzy" + tenantName: 'Default', + userName: 'Default', + resetLink: 'https://github.com/ever-co/ever-gauzy' } ], companyLink, diff --git a/packages/core/src/lib/invite/invite.service.ts b/packages/core/src/lib/invite/invite.service.ts index 594e92c4cdf..8d2089dd3db 100644 --- a/packages/core/src/lib/invite/invite.service.ts +++ b/packages/core/src/lib/invite/invite.service.ts @@ -5,7 +5,7 @@ import { FindManyOptions, FindOptionsWhere, In, IsNull, MoreThanOrEqual, Not, Se import { addDays } from 'date-fns'; import { pick } from 'underscore'; import { ConfigService, environment } from '@gauzy/config'; -import { DEFAULT_INVITE_EXPIRY_PERIOD } from '@gauzy/constants'; +import { ALPHA_NUMERIC_CODE_LENGTH, DEFAULT_INVITE_EXPIRY_PERIOD } from '@gauzy/constants'; import { ICreateEmailInvitesInput, ICreateEmailInvitesOutput, @@ -28,17 +28,10 @@ import { IPagination } from '@gauzy/contracts'; import { IAppIntegrationConfig } from '@gauzy/common'; -import { isNotEmpty } from '@gauzy/utils'; +import { generateAlphaNumericCode, isNotEmpty } from '@gauzy/utils'; import { PaginationParams, TenantAwareCrudService } from './../core/crud'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../constants'; import { RequestContext } from './../core/context'; -import { - MultiORMEnum, - freshTimestamp, - generateRandomAlphaNumericCode, - getArrayIntersection, - parseTypeORMFindToMikroOrm -} from './../core/utils'; +import { MultiORMEnum, freshTimestamp, getArrayIntersection, parseTypeORMFindToMikroOrm } from './../core/utils'; import { EmailService } from './../email-send/email.service'; import { UserService } from '../user/user.service'; import { RoleService } from './../role/role.service'; @@ -177,7 +170,7 @@ export class InviteService extends TenantAwareCrudService { const invites: Invite[] = []; for await (const email of emailIds) { let alreadyInTeamIds: string[] = []; - const code = generateRandomAlphaNumericCode(6); + const code = generateAlphaNumericCode(); const token: string = sign({ email, code }, environment.JWT_SECRET, {}); const organizationTeamEmployees = await this.typeOrmOrganizationTeamEmployeeRepository.find({ @@ -370,7 +363,7 @@ export class InviteService extends TenantAwareCrudService { */ const invitedBy: IUser = await this.userService.findOneByIdString(RequestContext.currentUserId()); try { - const code = generateRandomAlphaNumericCode(ALPHA_NUMERIC_CODE_LENGTH); + const code = generateAlphaNumericCode(); const token: string = sign({ email, code }, environment.JWT_SECRET, {}); const registerUrl = `${originUrl}/#/auth/accept-invite?email=${encodeURIComponent(email)}&token=${token}`; diff --git a/packages/core/src/lib/organization-team-join-request/dto/validate-join-request.dto.ts b/packages/core/src/lib/organization-team-join-request/dto/validate-join-request.dto.ts index 491a4cd0c47..7c3263ab85f 100644 --- a/packages/core/src/lib/organization-team-join-request/dto/validate-join-request.dto.ts +++ b/packages/core/src/lib/organization-team-join-request/dto/validate-join-request.dto.ts @@ -1,27 +1,26 @@ -import { ApiProperty, IntersectionType, PickType } from "@nestjs/swagger"; -import { IOrganizationTeamJoinRequestValidateInput } from "@gauzy/contracts"; -import { IsString, ValidateIf } from "class-validator"; -import { ALPHA_NUMERIC_CODE_LENGTH } from "./../../constants"; -import { CustomLength } from "../../shared/validators"; -import { UserEmailDTO } from "../../user/dto"; -import { OrganizationTeamJoinRequest } from "../organization-team-join-request.entity"; +import { ApiProperty, IntersectionType, PickType } from '@nestjs/swagger'; +import { IOrganizationTeamJoinRequestValidateInput } from '@gauzy/contracts'; +import { IsString, ValidateIf } from 'class-validator'; +import { ALPHA_NUMERIC_CODE_LENGTH } from '@gauzy/constants'; +import { CustomLength } from '../../shared/validators'; +import { UserEmailDTO } from '../../user/dto'; +import { OrganizationTeamJoinRequest } from '../organization-team-join-request.entity'; /** * Validate team join request DTO validation */ -export class ValidateJoinRequestDTO extends IntersectionType( - UserEmailDTO, - PickType(OrganizationTeamJoinRequest, ['organizationTeamId']) -) implements IOrganizationTeamJoinRequestValidateInput { +export class ValidateJoinRequestDTO + extends IntersectionType(UserEmailDTO, PickType(OrganizationTeamJoinRequest, ['organizationTeamId'])) + implements IOrganizationTeamJoinRequestValidateInput +{ + @ApiProperty({ type: () => String }) + @ValidateIf((it) => !it.token) + @IsString() + @CustomLength(ALPHA_NUMERIC_CODE_LENGTH) + readonly code: string; - @ApiProperty({ type: () => String }) - @ValidateIf((it) => !it.token) - @IsString() - @CustomLength(ALPHA_NUMERIC_CODE_LENGTH) - readonly code: string; - - @ApiProperty({ type: () => String }) - @ValidateIf((it) => !it.code) - @IsString() - readonly token: string; + @ApiProperty({ type: () => String }) + @ValidateIf((it) => !it.code) + @IsString() + readonly token: string; } diff --git a/packages/core/src/lib/organization-team-join-request/organization-team-join-request.service.ts b/packages/core/src/lib/organization-team-join-request/organization-team-join-request.service.ts index 8c8456b2838..5e6a5d6b87f 100644 --- a/packages/core/src/lib/organization-team-join-request/organization-team-join-request.service.ts +++ b/packages/core/src/lib/organization-team-join-request/organization-team-join-request.service.ts @@ -1,8 +1,9 @@ import { BadRequestException, ConflictException, Injectable, HttpStatus, NotFoundException } from '@nestjs/common'; import { MoreThanOrEqual, SelectQueryBuilder, IsNull, FindManyOptions } from 'typeorm'; import { JwtPayload, sign } from 'jsonwebtoken'; -import { environment } from '@gauzy/config'; +import * as moment from 'moment'; import { IAppIntegrationConfig } from '@gauzy/common'; +import { environment } from '@gauzy/config'; import { IOrganizationTeamJoinRequest, IOrganizationTeamJoinRequestCreateInput, @@ -13,10 +14,8 @@ import { OrganizationTeamJoinRequestStatusEnum, RolesEnum } from '@gauzy/contracts'; -import * as moment from 'moment'; -import { ALPHA_NUMERIC_CODE_LENGTH } from './../constants'; +import { generateAlphaNumericCode } from '@gauzy/utils'; import { TenantAwareCrudService } from './../core/crud'; -import { generateRandomAlphaNumericCode } from './../core/utils'; import { RequestContext } from './../core/context'; import { User } from './../core/entities/internal'; import { EmailService } from './../email-send/email.service'; @@ -92,7 +91,7 @@ export class OrganizationTeamJoinRequestService extends TenantAwareCrudService SetMetadata(PERMISSIONS_METADATA, permissions); diff --git a/packages/core/src/lib/shared/decorators/roles.decorator.ts b/packages/core/src/lib/shared/decorators/roles.decorator.ts index 7c16a254afb..a85ec2248f0 100644 --- a/packages/core/src/lib/shared/decorators/roles.decorator.ts +++ b/packages/core/src/lib/shared/decorators/roles.decorator.ts @@ -1,5 +1,5 @@ import { CustomDecorator, SetMetadata } from '@nestjs/common'; -import { ROLES_METADATA } from '@gauzy/common'; +import { ROLES_METADATA } from '@gauzy/constants'; import { RolesEnum } from '@gauzy/contracts'; export const Roles = (...roles: RolesEnum[]): CustomDecorator => SetMetadata(ROLES_METADATA, roles); diff --git a/packages/core/src/lib/shared/guards/auth.guard.ts b/packages/core/src/lib/shared/guards/auth.guard.ts index 38842e5e3bf..c3c96adad04 100644 --- a/packages/core/src/lib/shared/guards/auth.guard.ts +++ b/packages/core/src/lib/shared/guards/auth.guard.ts @@ -2,7 +2,7 @@ import { ContextType, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { GqlExecutionContext } from '@nestjs/graphql'; import { AuthGuard as PassportAuthGuard } from '@nestjs/passport'; -import { PUBLIC_METHOD_METADATA } from '@gauzy/common'; +import { PUBLIC_METHOD_METADATA } from '@gauzy/constants'; @Injectable() export class AuthGuard extends PassportAuthGuard('jwt') { diff --git a/packages/core/src/lib/shared/guards/feature-flag.guard.ts b/packages/core/src/lib/shared/guards/feature-flag.guard.ts index aab029698d6..dd1253a1f7a 100644 --- a/packages/core/src/lib/shared/guards/feature-flag.guard.ts +++ b/packages/core/src/lib/shared/guards/feature-flag.guard.ts @@ -2,7 +2,7 @@ import { CanActivate, ExecutionContext, Inject, Injectable, NotFoundException, T import { Reflector } from '@nestjs/core'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; -import { FEATURE_METADATA } from '@gauzy/common'; +import { FEATURE_METADATA } from '@gauzy/constants'; import { FeatureEnum } from '@gauzy/contracts'; import { FeatureService } from './../../feature/feature.service'; diff --git a/packages/core/src/lib/shared/guards/organization-permission.guard.ts b/packages/core/src/lib/shared/guards/organization-permission.guard.ts index 5cb636c4e8a..a2e795a6e12 100644 --- a/packages/core/src/lib/shared/guards/organization-permission.guard.ts +++ b/packages/core/src/lib/shared/guards/organization-permission.guard.ts @@ -6,7 +6,7 @@ import { Cache } from 'cache-manager'; import { Brackets, WhereExpressionBuilder } from 'typeorm'; import { verify } from 'jsonwebtoken'; import * as camelcase from 'camelcase'; -import { PERMISSIONS_METADATA } from '@gauzy/common'; +import { PERMISSIONS_METADATA } from '@gauzy/constants'; import { PermissionsEnum, RolesEnum } from '@gauzy/contracts'; import { deduplicate, isEmpty } from '@gauzy/utils'; import { RequestContext } from './../../core/context'; diff --git a/packages/core/src/lib/shared/guards/permission.guard.ts b/packages/core/src/lib/shared/guards/permission.guard.ts index e82b7ef69d8..3d615de114f 100644 --- a/packages/core/src/lib/shared/guards/permission.guard.ts +++ b/packages/core/src/lib/shared/guards/permission.guard.ts @@ -3,7 +3,7 @@ import { Reflector } from '@nestjs/core'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { verify } from 'jsonwebtoken'; -import { PERMISSIONS_METADATA } from '@gauzy/common'; +import { PERMISSIONS_METADATA } from '@gauzy/constants'; import { environment as env } from '@gauzy/config'; import { PermissionsEnum } from '@gauzy/contracts'; import { deduplicate, isEmpty } from '@gauzy/utils'; diff --git a/packages/core/src/lib/shared/guards/role.guard.ts b/packages/core/src/lib/shared/guards/role.guard.ts index c257f28cd2e..619535737fd 100644 --- a/packages/core/src/lib/shared/guards/role.guard.ts +++ b/packages/core/src/lib/shared/guards/role.guard.ts @@ -1,5 +1,5 @@ import { Injectable, CanActivate, ExecutionContext, Type } from '@nestjs/common'; -import { ROLES_METADATA } from '@gauzy/common'; +import { ROLES_METADATA } from '@gauzy/constants'; import { RolesEnum } from '@gauzy/contracts'; import { Reflector } from '@nestjs/core'; import { isEmpty } from '@gauzy/utils'; diff --git a/packages/core/src/lib/shared/guards/tenant-permission.guard.ts b/packages/core/src/lib/shared/guards/tenant-permission.guard.ts index eb601ff56f4..e34f0f88519 100644 --- a/packages/core/src/lib/shared/guards/tenant-permission.guard.ts +++ b/packages/core/src/lib/shared/guards/tenant-permission.guard.ts @@ -2,7 +2,7 @@ import { Injectable, CanActivate, ExecutionContext, Type, Inject } from '@nestjs import { Reflector } from '@nestjs/core'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; -import { PERMISSIONS_METADATA } from '@gauzy/common'; +import { PERMISSIONS_METADATA } from '@gauzy/constants'; import { environment as env } from '@gauzy/config'; import { PermissionsEnum, RolesEnum } from '@gauzy/contracts'; import { isNotEmpty, deduplicate } from '@gauzy/utils'; diff --git a/packages/core/src/lib/stats/stats.guard.ts b/packages/core/src/lib/stats/stats.guard.ts index 48770a528cf..946208edd11 100644 --- a/packages/core/src/lib/stats/stats.guard.ts +++ b/packages/core/src/lib/stats/stats.guard.ts @@ -1,7 +1,7 @@ import { CanActivate, ExecutionContext, Injectable, NotFoundException, Type } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; -import { FEATURE_METADATA } from '@gauzy/common'; import { gauzyToggleFeatures } from '@gauzy/config'; +import { FEATURE_METADATA } from '@gauzy/constants'; import { FeatureEnum } from '@gauzy/contracts'; @Injectable() diff --git a/packages/core/src/lib/user/dto/user-code.dto.ts b/packages/core/src/lib/user/dto/user-code.dto.ts index 0957a2649a3..c76610da5f5 100644 --- a/packages/core/src/lib/user/dto/user-code.dto.ts +++ b/packages/core/src/lib/user/dto/user-code.dto.ts @@ -1,16 +1,15 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { IsString } from "class-validator"; -import { IUserCodeInput } from "@gauzy/contracts"; -import { ALPHA_NUMERIC_CODE_LENGTH } from "./../../constants"; -import { CustomLength } from "./../../shared/validators"; +import { ApiProperty } from '@nestjs/swagger'; +import { IsString } from 'class-validator'; +import { IUserCodeInput } from '@gauzy/contracts'; +import { ALPHA_NUMERIC_CODE_LENGTH } from '@gauzy/constants'; +import { CustomLength } from './../../shared/validators'; /** * User code input DTO validation */ export class UserCodeDTO implements IUserCodeInput { - - @ApiProperty({ type: () => Number }) - @IsString() - @CustomLength(ALPHA_NUMERIC_CODE_LENGTH) - readonly code: string; + @ApiProperty({ type: () => Number }) + @IsString() + @CustomLength(ALPHA_NUMERIC_CODE_LENGTH) + readonly code: string; } diff --git a/packages/plugin/src/lib/constants.ts b/packages/plugin/src/lib/constants.ts deleted file mode 100644 index 38a05d20acd..00000000000 --- a/packages/plugin/src/lib/constants.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const PLUGIN_METADATA = { - ENTITIES: 'entities', - EXTENSIONS: 'extensions' -}; diff --git a/packages/plugin/src/lib/plugin-metadata.ts b/packages/plugin/src/lib/plugin-metadata.ts index 7642f365381..9eae5de0a8f 100644 --- a/packages/plugin/src/lib/plugin-metadata.ts +++ b/packages/plugin/src/lib/plugin-metadata.ts @@ -1,9 +1,29 @@ /** - * Metadata keys used in plugins. + * Metadata keys used in plugins for defining various aspects like entities, subscribers, and configurations. */ export const PLUGIN_METADATA = { + /** + * Key representing the entities registered within the plugin. + */ ENTITIES: 'entities', + + /** + * Key representing event subscribers within the plugin. + */ SUBSCRIBERS: 'subscribers', + + /** + * Key representing the extensions registered within the plugin. + */ EXTENSIONS: 'extensions', + + /** + * Key representing configuration settings of the plugin. + */ CONFIGURATION: 'configuration' -}; +} as const; + +/** + * Type definition for valid plugin metadata keys. + */ +export type PluginMetadataKey = (typeof PLUGIN_METADATA)[keyof typeof PLUGIN_METADATA]; diff --git a/packages/plugin/src/lib/plugin.ts b/packages/plugin/src/lib/plugin.ts index a2b3498354c..cbc4daf7562 100644 --- a/packages/plugin/src/lib/plugin.ts +++ b/packages/plugin/src/lib/plugin.ts @@ -10,9 +10,7 @@ import { PLUGIN_METADATA } from './plugin-metadata'; * @param pluginMetadata Metadata to be applied to the target class. * @returns Class decorator function. */ -export function GauzyCorePlugin( - pluginMetadata: PluginMetadata -): ClassDecorator { +export function GauzyCorePlugin(pluginMetadata: PluginMetadata): ClassDecorator { return (targetClass) => { // Iterate over properties in PLUGIN_METADATA for (const metadataProperty of Object.values(PLUGIN_METADATA)) { diff --git a/packages/plugins/integration-ai/src/lib/constants.ts b/packages/plugins/integration-ai/src/lib/constants.ts deleted file mode 100644 index 2236fe65052..00000000000 --- a/packages/plugins/integration-ai/src/lib/constants.ts +++ /dev/null @@ -1 +0,0 @@ -export const GAUZY_AI_CONFIG_OPTIONS = 'GAUZY_AI_CONFIG_OPTIONS'; diff --git a/packages/plugins/integration-ai/src/lib/gauzy-ai.module.ts b/packages/plugins/integration-ai/src/lib/gauzy-ai.module.ts index 486bebffb6b..31f25f48180 100644 --- a/packages/plugins/integration-ai/src/lib/gauzy-ai.module.ts +++ b/packages/plugins/integration-ai/src/lib/gauzy-ai.module.ts @@ -1,11 +1,11 @@ import { ConfigModule, ConfigService } from '@nestjs/config'; import { HttpModule } from '@nestjs/axios'; import { DynamicModule, Module } from '@nestjs/common'; +import { GAUZY_AI_CONFIG_TOKEN } from '@gauzy/constants'; import { GauzyAIService } from './gauzy-ai.service'; import gauzyAI from './config/gauzy-ai'; import { IConfigurationOptions } from './configuration.interface'; import { RequestConfigProvider } from './request-config.provider'; -import { GAUZY_AI_CONFIG_OPTIONS } from './constants'; @Module({ imports: [ @@ -41,7 +41,7 @@ export class GauzyAIModule { imports: [ConfigModule], // Make sure to import ConfigModule here providers: [ { - provide: GAUZY_AI_CONFIG_OPTIONS, + provide: GAUZY_AI_CONFIG_TOKEN, useFactory: (config: ConfigService): IConfigurationOptions => ({ apiKey: config.get('gauzyAI.gauzyAiApiKey'), apiSecret: config.get('gauzyAI.gauzyAiApiSecret'), @@ -50,7 +50,7 @@ export class GauzyAIModule { inject: [ConfigService] } ], - exports: [GAUZY_AI_CONFIG_OPTIONS] + exports: [GAUZY_AI_CONFIG_TOKEN] }; } } diff --git a/packages/plugins/integration-ai/src/lib/request-config.provider.ts b/packages/plugins/integration-ai/src/lib/request-config.provider.ts index f696666652c..45a1ac32ae0 100644 --- a/packages/plugins/integration-ai/src/lib/request-config.provider.ts +++ b/packages/plugins/integration-ai/src/lib/request-config.provider.ts @@ -1,6 +1,6 @@ import { Inject, Injectable } from '@nestjs/common'; +import { GAUZY_AI_CONFIG_TOKEN } from '@gauzy/constants'; import { IConfigurationOptions } from './configuration.interface'; -import { GAUZY_AI_CONFIG_OPTIONS } from './constants'; @Injectable() export class RequestConfigProvider { @@ -8,7 +8,7 @@ export class RequestConfigProvider { private config: IConfigurationOptions = new Object(); constructor( - @Inject(GAUZY_AI_CONFIG_OPTIONS) + @Inject(GAUZY_AI_CONFIG_TOKEN) protected readonly options: IConfigurationOptions ) { this.setDefaultConfig(options); diff --git a/packages/plugins/integration-github-ui/src/lib/components/view/view.component.ts b/packages/plugins/integration-github-ui/src/lib/components/view/view.component.ts index 8c7856a5ff4..a7fc08087d3 100644 --- a/packages/plugins/integration-github-ui/src/lib/components/view/view.component.ts +++ b/packages/plugins/integration-github-ui/src/lib/components/view/view.component.ts @@ -8,6 +8,7 @@ import { TranslateService } from '@ngx-translate/core'; import { NbPopoverDirective, NbTabComponent } from '@nebular/theme'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { Angular2SmartTableComponent, Cell } from 'angular2-smart-table'; +import { SyncTags } from '@gauzy/constants'; import { GithubRepositoryStatusEnum, HttpStatus, @@ -19,7 +20,6 @@ import { IOrganizationGithubRepository, IOrganizationProject, IUser, - SYNC_TAG_GAUZY, TaskStatusEnum } from '@gauzy/contracts'; import { @@ -595,7 +595,7 @@ export class GithubViewComponent extends PaginationFilterBaseComponent implement organizationId, tenantId, customFields: { repositoryId }, - syncTag: SYNC_TAG_GAUZY + syncTag: SyncTags.GAUZY }); const issues$ = this._githubService.autoSyncIssues(integrationId, repository, { projectId, @@ -682,7 +682,7 @@ export class GithubViewComponent extends PaginationFilterBaseComponent implement organizationId, tenantId, customFields: { repositoryId }, - syncTag: SYNC_TAG_GAUZY + syncTag: SyncTags.GAUZY }) ), mergeMap(() => diff --git a/packages/plugins/integration-github/src/lib/github/github-sync.service.ts b/packages/plugins/integration-github/src/lib/github/github-sync.service.ts index 5f1dad4b466..7c1c46ec610 100644 --- a/packages/plugins/integration-github/src/lib/github/github-sync.service.ts +++ b/packages/plugins/integration-github/src/lib/github/github-sync.service.ts @@ -3,6 +3,7 @@ import { CommandBus } from '@nestjs/cqrs'; import * as moment from 'moment'; import * as chalk from 'chalk'; import { Request } from 'express'; +import { SyncTags } from '@gauzy/constants'; import { IGithubAutomationIssuePayload, IGithubIssue, @@ -19,8 +20,6 @@ import { IOrganizationGithubRepository, IIntegrationMap, GithubRepositoryStatusEnum, - SYNC_TAG_GAUZY, - SYNC_TAG_GITHUB, ID } from '@gauzy/contracts'; import { @@ -379,7 +378,7 @@ export class GithubSyncService { let labels = issue.labels; // List of labels to check and create if missing - const labelsToCheck = [SYNC_TAG_GITHUB, SYNC_TAG_GAUZY]; + const labelsToCheck = [SyncTags.GITHUB, SyncTags.GAUZY]; const labelsToCreate = labelsToCheck.filter( (name) => !labels.find((label: IGithubIssueLabel) => label.name === name) ); diff --git a/packages/ui-core/shared/src/lib/project/project-mutation/project-mutation.component.ts b/packages/ui-core/shared/src/lib/project/project-mutation/project-mutation.component.ts index 7a11025b1d5..1072adaee2d 100644 --- a/packages/ui-core/shared/src/lib/project/project-mutation/project-mutation.component.ts +++ b/packages/ui-core/shared/src/lib/project/project-mutation/project-mutation.component.ts @@ -8,7 +8,7 @@ import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { TranslateService } from '@ngx-translate/core'; import { Router } from '@angular/router'; import { uniq } from 'underscore'; -import { environment } from '@gauzy/ui-config'; +import { SyncTags } from '@gauzy/constants'; import { IOrganization, IOrganizationContact, @@ -28,10 +28,11 @@ import { IOrganizationProjectSetting, IIntegrationMapSyncRepository, IOrganizationGithubRepository, - SYNC_TAG_GAUZY, IOrganizationProjectEmployee, ID } from '@gauzy/contracts'; +import { environment } from '@gauzy/ui-config'; +import { DUMMY_PROFILE_IMAGE, distinctUntilChange } from '@gauzy/ui-core/common'; import { GithubService, OrganizationContactService, @@ -42,7 +43,6 @@ import { ToastrService, Store } from '@gauzy/ui-core/core'; -import { DUMMY_PROFILE_IMAGE, distinctUntilChange } from '@gauzy/ui-core/common'; import { TranslationBaseComponent } from '@gauzy/ui-core/i18n'; import { patterns } from '../../regex/regex-patterns.const'; import { FormHelpers } from '../../forms/helpers'; @@ -622,7 +622,7 @@ export class ProjectMutationComponent extends TranslationBaseComponent implement organizationId, tenantId, customFields: { repositoryId }, - ...(!this.projectSettingForm.get('syncTag').value ? { syncTag: SYNC_TAG_GAUZY } : {}) + ...(!this.projectSettingForm.get('syncTag').value ? { syncTag: SyncTags.GAUZY } : {}) }); }), tap(() => { diff --git a/packages/utils/package.json b/packages/utils/package.json index fbfea3a3332..8a4165773bc 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -27,6 +27,7 @@ "lib:watch": "yarn nx build utils --watch" }, "dependencies": { + "@gauzy/constants": "^0.1.0", "generate-password": "^1.7.1", "slugify": "^1.6.6", "tslib": "^2.6.2" diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index e49720f1221..6184f3cd55e 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,3 +1,4 @@ +export * from './lib/array-to-object'; export * from './lib/array-sum'; export * from './lib/array-random-element'; export * from './lib/average'; @@ -5,6 +6,7 @@ export * from './lib/build-query-string'; export * from './lib/camel-to-snake-case'; export * from './lib/chunks'; export * from './lib/class-mixins'; +export * from './lib/code-generator'; export * from './lib/convert-to-hex'; export * from './lib/deduplicate'; export * from './lib/deep-clone'; diff --git a/packages/utils/src/lib/array-to-object.ts b/packages/utils/src/lib/array-to-object.ts new file mode 100644 index 00000000000..dac577f356e --- /dev/null +++ b/packages/utils/src/lib/array-to-object.ts @@ -0,0 +1,30 @@ +/** + * Converts an array of objects into a key-value object based on specified properties. + * + * @template T - Type of objects within the array. + * @template K - Key property type (extends keyof T). + * @template V - Value property type (extends keyof T). + * + * @param {T[]} array - The input array of objects. + * @param {K} key - The property name to be used as the object key. + * @param {V} value - The property name to be used as the object value. + * @returns {Record} - The resulting object mapping keys to values. + * + * @example + * const users = [ + * { id: 1, name: 'John' }, + * { id: 2, name: 'Jane' } + * ]; + * const userMap = arrayToObject(users, 'id', 'name'); + * console.log(userMap); // { "1": "John", "2": "Jane" } + */ +export function arrayToObject( + array: T[], + key: K, + value: V +): Record { + return array.reduce((acc: Record, item: T) => { + acc[String(item[key])] = item[value]; + return acc; + }, {}); +} diff --git a/packages/utils/src/lib/code-generator.ts b/packages/utils/src/lib/code-generator.ts new file mode 100644 index 00000000000..34587bf936f --- /dev/null +++ b/packages/utils/src/lib/code-generator.ts @@ -0,0 +1,19 @@ +import { ALPHA_NUMERIC_CODE_LENGTH } from '@gauzy/constants'; + +/** + * Generates a random alphanumeric code. + * + * @param length - The length of the code. Default is `ALPHA_NUMERIC_CODE_LENGTH` (6). + * @returns A randomly generated alphanumeric code. + */ +export function generateAlphaNumericCode(length: number = ALPHA_NUMERIC_CODE_LENGTH): string { + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + + for (let i = 0; i < length; i++) { + const index = Math.floor(Math.random() * characters.length); + code += characters[index]; + } + + return code; +} From ca5b0728772cdefabdbfa3677bb49866733cf3a4 Mon Sep 17 00:00:00 2001 From: "Rahul R." Date: Fri, 24 Jan 2025 13:11:00 +0530 Subject: [PATCH 2/4] fix(deepscan): removed unused import :) --- packages/core/src/lib/core/utils.ts | 1 - packages/core/src/lib/invite/invite.service.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/core/src/lib/core/utils.ts b/packages/core/src/lib/core/utils.ts index 970fe0189b0..17b7a949b05 100644 --- a/packages/core/src/lib/core/utils.ts +++ b/packages/core/src/lib/core/utils.ts @@ -15,7 +15,6 @@ import { sample } from 'underscore'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; -import { ALPHA_NUMERIC_CODE_LENGTH } from '@gauzy/constants'; import { DateRange, IDateRange, IUser } from '@gauzy/contracts'; import { IDBConnectionOptions } from '@gauzy/common'; import { getConfig, DatabaseTypeEnum } from '@gauzy/config'; diff --git a/packages/core/src/lib/invite/invite.service.ts b/packages/core/src/lib/invite/invite.service.ts index 8d2089dd3db..9404db55856 100644 --- a/packages/core/src/lib/invite/invite.service.ts +++ b/packages/core/src/lib/invite/invite.service.ts @@ -5,7 +5,7 @@ import { FindManyOptions, FindOptionsWhere, In, IsNull, MoreThanOrEqual, Not, Se import { addDays } from 'date-fns'; import { pick } from 'underscore'; import { ConfigService, environment } from '@gauzy/config'; -import { ALPHA_NUMERIC_CODE_LENGTH, DEFAULT_INVITE_EXPIRY_PERIOD } from '@gauzy/constants'; +import { DEFAULT_INVITE_EXPIRY_PERIOD } from '@gauzy/constants'; import { ICreateEmailInvitesInput, ICreateEmailInvitesOutput, From 601e6e1698ecafb0c4559534bb2cccc2451f7e9f Mon Sep 17 00:00:00 2001 From: "Rahul R." Date: Fri, 24 Jan 2025 14:05:14 +0530 Subject: [PATCH 3/4] fix: packages build issue --- apps/api/src/plugin-config.ts | 11 +++------- .../src/lib/integration-ai.middleware.ts | 4 ++-- .../src/lib/integration-ai.service.ts | 3 +-- .../plugins/integration-github/package.json | 1 + .../github-installation.delete.handler.ts | 2 +- .../handlers/task.update-or-create.handler.ts | 4 ++-- .../src/lib/github/github-sync.service.ts | 5 ++--- .../src/lib/github/github.middleware.ts | 4 ++-- .../src/lib/github/github.service.ts | 6 +++--- .../src/lib/upwork.service.ts | 16 +++++++------- .../common/src/lib/utils/shared-utils.ts | 21 ------------------- 11 files changed, 26 insertions(+), 51 deletions(-) diff --git a/apps/api/src/plugin-config.ts b/apps/api/src/plugin-config.ts index df87d5a150f..b60f9712e3e 100644 --- a/apps/api/src/plugin-config.ts +++ b/apps/api/src/plugin-config.ts @@ -1,12 +1,7 @@ import * as path from 'path'; import * as chalk from 'chalk'; -import { - ApplicationPluginConfig, - DEFAULT_API_PORT, - DEFAULT_GRAPHQL_API_PATH, - DEFAULT_API_HOST, - DEFAULT_API_BASE_URL -} from '@gauzy/common'; +import { ApplicationPluginConfig } from '@gauzy/common'; +import { DEFAULT_API_PORT, DEFAULT_GRAPHQL_API_PATH, DEFAULT_API_HOST, DEFAULT_API_BASE_URL } from '@gauzy/constants'; import { dbTypeOrmConnectionConfig, dbMikroOrmConnectionConfig, @@ -61,7 +56,7 @@ console.log('Plugin Config -> assetPublicPath: ' + assetPublicPath); console.log('DB Synchronize: ' + process.env.DB_SYNCHRONIZE); /** - * Application plugin configuration + * Application plugin configuration for production environment. */ export const pluginConfig: ApplicationPluginConfig = { apiConfigOptions: { diff --git a/packages/plugins/integration-ai/src/lib/integration-ai.middleware.ts b/packages/plugins/integration-ai/src/lib/integration-ai.middleware.ts index 4af0ac826fd..793765b94b6 100644 --- a/packages/plugins/integration-ai/src/lib/integration-ai.middleware.ts +++ b/packages/plugins/integration-ai/src/lib/integration-ai.middleware.ts @@ -3,8 +3,8 @@ import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { Request, Response, NextFunction } from 'express'; import { IIntegrationSetting, IntegrationEnum } from '@gauzy/contracts'; -import { isNotEmpty } from '@gauzy/utils'; -import { arrayToObject, IntegrationTenantService } from '@gauzy/core'; +import { arrayToObject, isNotEmpty } from '@gauzy/utils'; +import { IntegrationTenantService } from '@gauzy/core'; import { RequestConfigProvider } from './request-config.provider'; @Injectable() diff --git a/packages/plugins/integration-ai/src/lib/integration-ai.service.ts b/packages/plugins/integration-ai/src/lib/integration-ai.service.ts index 7cbbc7a3ae7..285fa674423 100644 --- a/packages/plugins/integration-ai/src/lib/integration-ai.service.ts +++ b/packages/plugins/integration-ai/src/lib/integration-ai.service.ts @@ -7,9 +7,8 @@ import { IIntegrationTenantUpdateInput, IntegrationEnum } from '@gauzy/contracts'; -import { isNotEmpty } from '@gauzy/utils'; +import { arrayToObject, isNotEmpty } from '@gauzy/utils'; import { - arrayToObject, IntegrationService, IntegrationTenantService, IntegrationTenantUpdateOrCreateCommand, diff --git a/packages/plugins/integration-github/package.json b/packages/plugins/integration-github/package.json index 94a462621e9..09d7f50f20f 100644 --- a/packages/plugins/integration-github/package.json +++ b/packages/plugins/integration-github/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@gauzy/config": "^0.1.0", + "@gauzy/constants": "^0.1.0", "@gauzy/contracts": "^0.1.0", "@gauzy/core": "^0.1.0", "@gauzy/plugin": "^0.1.0", diff --git a/packages/plugins/integration-github/src/lib/github/commands/handlers/github-installation.delete.handler.ts b/packages/plugins/integration-github/src/lib/github/commands/handlers/github-installation.delete.handler.ts index f1fdb7b3fbd..cb3192fa1a4 100644 --- a/packages/plugins/integration-github/src/lib/github/commands/handlers/github-installation.delete.handler.ts +++ b/packages/plugins/integration-github/src/lib/github/commands/handlers/github-installation.delete.handler.ts @@ -1,6 +1,6 @@ import { HttpException, HttpStatus } from '@nestjs/common'; import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; -import { arrayToObject } from '@gauzy/core'; +import { arrayToObject } from '@gauzy/utils'; import { OctokitService } from '../../../probot/octokit.service'; import { GithubInstallationDeleteCommand } from '../github-installation.delete.command'; diff --git a/packages/plugins/integration-github/src/lib/github/commands/handlers/task.update-or-create.handler.ts b/packages/plugins/integration-github/src/lib/github/commands/handlers/task.update-or-create.handler.ts index 54fe67a4656..ec0d0138e39 100644 --- a/packages/plugins/integration-github/src/lib/github/commands/handlers/task.update-or-create.handler.ts +++ b/packages/plugins/integration-github/src/lib/github/commands/handlers/task.update-or-create.handler.ts @@ -14,9 +14,9 @@ import { IntegrationMapSyncEntityCommand, IntegrationTenantGetCommand, OrganizationProjectService, - RequestContext, - arrayToObject + RequestContext } from '@gauzy/core'; +import { arrayToObject } from '@gauzy/utils'; import { GithubRepositoryIssueService } from './../../repository/issue/github-repository-issue.service'; import { IntegrationSyncGithubRepositoryIssueCommand } from '../../repository/issue/commands'; import { GithubSyncService } from '../../github-sync.service'; diff --git a/packages/plugins/integration-github/src/lib/github/github-sync.service.ts b/packages/plugins/integration-github/src/lib/github/github-sync.service.ts index 7c1c46ec610..34c487e941a 100644 --- a/packages/plugins/integration-github/src/lib/github/github-sync.service.ts +++ b/packages/plugins/integration-github/src/lib/github/github-sync.service.ts @@ -29,10 +29,9 @@ import { IntegrationMapSyncLabelCommand, IntegrationTenantService, OrganizationProjectService, - RequestContext, - arrayToObject + RequestContext } from '@gauzy/core'; -import { isNotEmpty, sleep } from '@gauzy/utils'; +import { arrayToObject, isNotEmpty, sleep } from '@gauzy/utils'; import { OctokitService } from '../probot/octokit.service'; import { GithubRepositoryService } from './repository/github-repository.service'; import { IntegrationSyncGithubRepositoryIssueCommand } from './repository/issue/commands'; diff --git a/packages/plugins/integration-github/src/lib/github/github.middleware.ts b/packages/plugins/integration-github/src/lib/github/github.middleware.ts index e0cda152432..13b297e2777 100644 --- a/packages/plugins/integration-github/src/lib/github/github.middleware.ts +++ b/packages/plugins/integration-github/src/lib/github/github.middleware.ts @@ -2,9 +2,9 @@ import { Inject, Injectable, NestMiddleware } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { Request, Response, NextFunction } from 'express'; -import { isNotEmpty } from '@gauzy/utils'; import { IIntegrationSetting, IntegrationEnum } from '@gauzy/contracts'; -import { IntegrationTenantService, arrayToObject } from '@gauzy/core'; +import { IntegrationTenantService } from '@gauzy/core'; +import { arrayToObject, isNotEmpty } from '@gauzy/utils'; @Injectable() export class GithubMiddleware implements NestMiddleware { diff --git a/packages/plugins/integration-github/src/lib/github/github.service.ts b/packages/plugins/integration-github/src/lib/github/github.service.ts index ede1ae8f587..4b50358f9e9 100644 --- a/packages/plugins/integration-github/src/lib/github/github.service.ts +++ b/packages/plugins/integration-github/src/lib/github/github.service.ts @@ -3,14 +3,14 @@ import { CommandBus } from '@nestjs/cqrs'; import { HttpService } from '@nestjs/axios'; import { firstValueFrom, switchMap } from 'rxjs'; import { environment } from '@gauzy/config'; +import { SyncTags } from '@gauzy/constants'; import { GithubPropertyMapEnum, IGithubAppInstallInput, IIntegrationTenant, IOAuthAppInstallInput, IntegrationEntity, - IntegrationEnum, - SYNC_TAG_GITHUB + IntegrationEnum } from '@gauzy/contracts'; import { IntegrationService, IntegrationTenantUpdateOrCreateCommand, RequestContext } from '@gauzy/core'; import { DEFAULT_ENTITY_SETTINGS, ISSUE_TIED_ENTITIES } from './github-entity-settings'; @@ -98,7 +98,7 @@ export class GithubService { }, { settingsName: GithubPropertyMapEnum.SYNC_TAG, - settingsValue: SYNC_TAG_GITHUB + settingsValue: SyncTags.GITHUB } ].map((setting) => ({ ...setting, diff --git a/packages/plugins/integration-upwork/src/lib/upwork.service.ts b/packages/plugins/integration-upwork/src/lib/upwork.service.ts index c51be99a4ea..46f7e5a1755 100644 --- a/packages/plugins/integration-upwork/src/lib/upwork.service.ts +++ b/packages/plugins/integration-upwork/src/lib/upwork.service.ts @@ -9,7 +9,6 @@ import { Auth } from 'upwork-api/lib/routers/auth.js'; import { Users } from 'upwork-api/lib/routers/organization/users.js'; import { pluck, map, sortBy } from 'underscore'; import * as moment from 'moment'; -import { isEmpty, isNotEmpty, isObject } from '@gauzy/utils'; import { environment } from '@gauzy/config'; import { IAccessTokenSecretPair, @@ -37,9 +36,10 @@ import { IPagination, IDateRange, ComponentLayoutStyleEnum, - ITimeLog + ITimeLog, + IIntegrationSetting } from '@gauzy/contracts'; -import { RequestContext, arrayToObject, mergeOverlappingDateRanges, unixTimestampToDate } from '@gauzy/core'; +import { RequestContext, mergeOverlappingDateRanges, unixTimestampToDate } from '@gauzy/core'; import { ExpenseService, IncomeService, @@ -70,6 +70,7 @@ import { TimeLogCreateCommand, TimeSlotCreateCommand } from '@gauzy/core'; +import { arrayToObject, isEmpty, isNotEmpty, isObject } from '@gauzy/utils'; import { ProposalCreateCommand } from '@gauzy/plugin-job-proposal'; import { UpworkReportService } from './upwork-report.service'; import { UpworkJobService } from './upwork-job.service'; @@ -107,7 +108,7 @@ export class UpworkService { return false; } - const integrationSettings = await this._commandBus.execute( + const integrationSettings: IIntegrationSetting[] = await this._commandBus.execute( new IntegrationSettingGetManyCommand({ where: { integration: integrationSetting.integration, @@ -120,6 +121,7 @@ export class UpworkService { } const integrationSettingMap = arrayToObject(integrationSettings, 'settingsName', 'settingsValue'); + if (integrationSettingMap.accessToken && integrationSettingMap.accessTokenSecret) { return { integrationId: integrationSetting.integration.id, @@ -139,7 +141,7 @@ export class UpworkService { // access token live forever, if user already registered app, return the access token; if (consumerAccessToken) { console.log('consumerAccessToken already exits and will be reused'); - return consumerAccessToken; + return; } const tenantId = RequestContext.currentTenantId(); @@ -217,7 +219,7 @@ export class UpworkService { relations: ['integration'] }) ); - const integrationSettings = await this._commandBus.execute( + const integrationSettings: IIntegrationSetting[] = await this._commandBus.execute( new IntegrationSettingGetManyCommand({ where: { integration, @@ -276,7 +278,7 @@ export class UpworkService { } }) ); - const integrationSettings = await this._commandBus.execute( + const integrationSettings: IIntegrationSetting[] = await this._commandBus.execute( new IntegrationSettingGetManyCommand({ where: { integration, diff --git a/packages/ui-core/common/src/lib/utils/shared-utils.ts b/packages/ui-core/common/src/lib/utils/shared-utils.ts index 363dbb127cb..01326886a31 100644 --- a/packages/ui-core/common/src/lib/utils/shared-utils.ts +++ b/packages/ui-core/common/src/lib/utils/shared-utils.ts @@ -458,27 +458,6 @@ export function sleep(ms: number) { return new Promise((r) => setTimeout(r, ms)); } -/** - * Convert an array of objects to an object with specified key-value pairs. - * - * @param array - The array of objects. - * @param key - The property to use as the key in the resulting object. - * @param value - The property to use as the value in the resulting object. - * @returns An object with key-value pairs based on the specified properties. - */ -export function arrayToObject>( - array: T[], - key: keyof T, - value: keyof T -): Record { - return array.reduce((prev, current) => { - return { - ...prev, - [String(current[key])]: current[value] - }; - }, {}); -} - /** * Converts a given input into a boolean value. * If the input is `undefined` or `null`, it returns `false`. From ba8db696f29287bdc6a0670d08da80fabca91de5 Mon Sep 17 00:00:00 2001 From: "Rahul R." Date: Fri, 24 Jan 2025 14:09:12 +0530 Subject: [PATCH 4/4] fix: apply suggestions by coderabbitai --- .../core/src/lib/invite/invite.service.ts | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/core/src/lib/invite/invite.service.ts b/packages/core/src/lib/invite/invite.service.ts index 9404db55856..cad6c088a5b 100644 --- a/packages/core/src/lib/invite/invite.service.ts +++ b/packages/core/src/lib/invite/invite.service.ts @@ -219,7 +219,7 @@ export class InviteService extends TenantAwareCrudService { }) ); } else { - ignoreInvites++; + ignoreInvites; } } else { invites.push( @@ -336,6 +336,22 @@ export class InviteService extends TenantAwareCrudService { .join('&'); } + /** + * Generates an invite code and a secure JWT token for email-based invites. + * + * @param {string} email - The email address for which the invite code and token are generated. + * @returns {{ code: string; token: string }} - An object containing the invite code and JWT token. + */ + private generateInviteCodeAndToken(email: string): { code: string; token: string } { + // Generate a unique invite code + const code = generateAlphaNumericCode(); + + // Generate a JWT token containing the email and invite code + const token = sign({ email, code }, environment.JWT_SECRET, {}); + + return { code, token }; + } + async resendEmail(input: IInviteResendInput, languageCode: LanguagesEnum) { const originUrl = this.configService.get('clientBaseUrl') as string; const { inviteId, inviteType, callbackUrl } = input; @@ -363,8 +379,7 @@ export class InviteService extends TenantAwareCrudService { */ const invitedBy: IUser = await this.userService.findOneByIdString(RequestContext.currentUserId()); try { - const code = generateAlphaNumericCode(); - const token: string = sign({ email, code }, environment.JWT_SECRET, {}); + const { code, token } = this.generateInviteCodeAndToken(email); const registerUrl = `${originUrl}/#/auth/accept-invite?email=${encodeURIComponent(email)}&token=${token}`; if (inviteType === InvitationTypeEnum.USER) {