@intlayer/backend 4.1.7 → 4.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/controllers/ai.controller.cjs +5 -5
- package/dist/cjs/controllers/dictionary.controller.cjs +53 -9
- package/dist/cjs/controllers/dictionary.controller.cjs.map +1 -1
- package/dist/cjs/controllers/event-listener.cjs +80 -0
- package/dist/cjs/controllers/event-listener.cjs.map +1 -0
- package/dist/cjs/controllers/oAuth2.controller.cjs +1 -1
- package/dist/cjs/controllers/oAuth2.controller.cjs.map +1 -1
- package/dist/cjs/controllers/organization.controller.cjs +1 -1
- package/dist/cjs/controllers/project.controller.cjs +1 -1
- package/dist/cjs/controllers/projectAccessKey.controller.cjs +1 -1
- package/dist/cjs/controllers/sessionAuth.controller.cjs +1 -1
- package/dist/cjs/controllers/stripe.controller.cjs +3 -2
- package/dist/cjs/controllers/stripe.controller.cjs.map +1 -1
- package/dist/cjs/controllers/tag.controller.cjs +1 -1
- package/dist/cjs/controllers/user.controller.cjs +1 -1
- package/dist/cjs/index.cjs +7 -6
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/routes/event-listener.routes.cjs +45 -0
- package/dist/cjs/routes/event-listener.routes.cjs.map +1 -0
- package/dist/cjs/services/dictionary.service.cjs +1 -1
- package/dist/cjs/services/oAuth2.service.cjs +13 -10
- package/dist/cjs/services/oAuth2.service.cjs.map +1 -1
- package/dist/cjs/services/organization.service.cjs +1 -1
- package/dist/cjs/services/project.service.cjs +1 -1
- package/dist/cjs/services/projectAccessKey.service.cjs +2 -2
- package/dist/cjs/services/projectAccessKey.service.cjs.map +1 -1
- package/dist/cjs/services/sessionAuth.service.cjs +1 -1
- package/dist/cjs/services/subscription.service.cjs +6 -6
- package/dist/cjs/services/subscription.service.cjs.map +1 -1
- package/dist/cjs/services/tag.service.cjs +1 -1
- package/dist/cjs/services/user.service.cjs +1 -1
- package/dist/cjs/types/oAuth2.types.cjs +17 -0
- package/dist/cjs/types/oAuth2.types.cjs.map +1 -0
- package/dist/cjs/utils/AI/askDocQuestion.cjs +7 -1
- package/dist/cjs/utils/AI/askDocQuestion.cjs.map +1 -1
- package/dist/cjs/utils/AI/embeddings.json +1845 -0
- package/dist/cjs/utils/errors/errorCodes.cjs +23 -1
- package/dist/cjs/utils/errors/errorCodes.cjs.map +1 -1
- package/dist/cjs/webhooks/stripe.webhook.cjs +3 -3
- package/dist/cjs/webhooks/stripe.webhook.cjs.map +1 -1
- package/dist/esm/controllers/ai.controller.mjs +5 -5
- package/dist/esm/controllers/dictionary.controller.mjs +53 -9
- package/dist/esm/controllers/dictionary.controller.mjs.map +1 -1
- package/dist/esm/controllers/event-listener.mjs +45 -0
- package/dist/esm/controllers/event-listener.mjs.map +1 -0
- package/dist/esm/controllers/oAuth2.controller.mjs +1 -1
- package/dist/esm/controllers/oAuth2.controller.mjs.map +1 -1
- package/dist/esm/controllers/organization.controller.mjs +1 -1
- package/dist/esm/controllers/project.controller.mjs +1 -1
- package/dist/esm/controllers/projectAccessKey.controller.mjs +1 -1
- package/dist/esm/controllers/sessionAuth.controller.mjs +1 -1
- package/dist/esm/controllers/stripe.controller.mjs +3 -2
- package/dist/esm/controllers/stripe.controller.mjs.map +1 -1
- package/dist/esm/controllers/tag.controller.mjs +1 -1
- package/dist/esm/controllers/user.controller.mjs +1 -1
- package/dist/esm/index.mjs +7 -6
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/routes/event-listener.routes.mjs +20 -0
- package/dist/esm/routes/event-listener.routes.mjs.map +1 -0
- package/dist/esm/services/dictionary.service.mjs +1 -1
- package/dist/esm/services/oAuth2.service.mjs +7 -4
- package/dist/esm/services/oAuth2.service.mjs.map +1 -1
- package/dist/esm/services/organization.service.mjs +1 -1
- package/dist/esm/services/project.service.mjs +1 -1
- package/dist/esm/services/projectAccessKey.service.mjs +2 -2
- package/dist/esm/services/projectAccessKey.service.mjs.map +1 -1
- package/dist/esm/services/sessionAuth.service.mjs +1 -1
- package/dist/esm/services/subscription.service.mjs +6 -6
- package/dist/esm/services/subscription.service.mjs.map +1 -1
- package/dist/esm/services/tag.service.mjs +1 -1
- package/dist/esm/services/user.service.mjs +1 -1
- package/dist/esm/types/oAuth2.types.mjs +1 -0
- package/dist/esm/types/oAuth2.types.mjs.map +1 -0
- package/dist/esm/utils/AI/askDocQuestion.mjs +7 -1
- package/dist/esm/utils/AI/askDocQuestion.mjs.map +1 -1
- package/dist/esm/utils/AI/embeddings.json +1845 -0
- package/dist/esm/utils/errors/errorCodes.mjs +23 -1
- package/dist/esm/utils/errors/errorCodes.mjs.map +1 -1
- package/dist/esm/webhooks/stripe.webhook.mjs +3 -3
- package/dist/esm/webhooks/stripe.webhook.mjs.map +1 -1
- package/dist/types/controllers/dictionary.controller.d.ts.map +1 -1
- package/dist/types/controllers/event-listener.d.ts +16 -0
- package/dist/types/controllers/event-listener.d.ts.map +1 -0
- package/dist/types/controllers/oAuth2.controller.d.ts +2 -5
- package/dist/types/controllers/oAuth2.controller.d.ts.map +1 -1
- package/dist/types/controllers/stripe.controller.d.ts.map +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/routes/event-listener.routes.d.ts +12 -0
- package/dist/types/routes/event-listener.routes.d.ts.map +1 -0
- package/dist/types/services/oAuth2.service.d.ts +6 -5
- package/dist/types/services/oAuth2.service.d.ts.map +1 -1
- package/dist/types/services/subscription.service.d.ts.map +1 -1
- package/dist/types/types/oAuth2.types.d.ts +11 -0
- package/dist/types/types/oAuth2.types.d.ts.map +1 -0
- package/dist/types/utils/AI/askDocQuestion.d.ts.map +1 -1
- package/dist/types/utils/errors/errorCodes.d.ts +23 -1
- package/dist/types/utils/errors/errorCodes.d.ts.map +1 -1
- package/dist/types/webhooks/stripe.webhook.d.ts.map +1 -1
- package/package.json +11 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/dictionary.controller.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { type Dictionary as LocalDictionary } from '@intlayer/core';\nimport { logger } from '@logger';\nimport type { ResponseWithInformation } from '@middlewares/sessionAuth.middleware';\nimport * as dictionaryService from '@services/dictionary.service';\nimport { AppError, ErrorHandler } from '@utils/errors';\nimport {\n type DictionaryFiltersParams,\n getDictionaryFiltersAndPagination,\n} from '@utils/filtersAndPagination/getDictionaryFiltersAndPagination';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport { mapDictionaryToAPI } from '@utils/mapper/dictionary';\nimport {\n formatPaginatedResponse,\n type ResponseData,\n type PaginatedResponse,\n formatResponse,\n} from '@utils/responseData';\nimport type { NextFunction, Request } from 'express';\nimport { t } from 'express-intlayer';\nimport type {\n Dictionary,\n DictionaryAPI,\n DictionaryCreationData,\n DictionaryData,\n VersionedContent,\n} from '@/types/dictionary.types';\n\nexport type GetDictionariesParams =\n FiltersAndPagination<DictionaryFiltersParams>;\nexport type GetDictionariesResult = PaginatedResponse<DictionaryAPI>;\n\n/**\n * Retrieves a list of dictionaries based on filters and pagination.\n */\nexport const getDictionaries = async (\n req: Request<GetDictionariesParams>,\n res: ResponseWithInformation<GetDictionariesResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, project, dictionaryRights } = res.locals;\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getDictionaryFiltersAndPagination(req);\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionaries = await dictionaryService.findDictionaries(\n filters,\n skip,\n pageSize\n );\n const totalItems = await dictionaryService.countDictionaries(filters);\n\n const dictionariesAPI = dictionaries.map((el) =>\n mapDictionaryToAPI(el, project._id, el.publishedVersion ?? undefined)\n );\n\n const responseData = formatPaginatedResponse<DictionaryAPI>({\n data: dictionariesAPI,\n page,\n pageSize,\n totalPages: getNumberOfPages(totalItems),\n totalItems,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetDictionariesKeysResult = ResponseData<string[]>;\n\n/**\n * Retrieves a list of dictionaries keys based on filters and pagination.\n */\nexport const getDictionariesKeys = async (\n _req: Request,\n res: ResponseWithInformation<GetDictionariesKeysResult>,\n _next: NextFunction\n) => {\n const { project, dictionaryRights } = res.locals;\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionariesKeys = await dictionaryService.getDictionariesKeys(\n project._id\n );\n\n const responseData = formatResponse<string[]>({\n data: dictionariesKeys,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetDictionaryParams = { dictionaryKey: string };\nexport type GetDictionaryQuery = { version?: string };\nexport type GetDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Retrieves a list of dictionaries based on filters and pagination.\n */\nexport const getDictionaryByKey = async (\n req: Request<GetDictionaryParams, any, any, GetDictionaryQuery>,\n res: ResponseWithInformation<GetDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const { dictionaryKey } = req.params;\n const version = req.query.version;\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionary = await dictionaryService.getDictionaryByKey(\n dictionaryKey,\n project._id\n );\n\n if (!dictionary.projectIds.map(String).includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'DICTIONARY_PROJECT_MISMATCH'\n );\n return;\n }\n\n const apiResult = mapDictionaryToAPI(dictionary, project._id, version);\n\n const responseData = formatResponse<DictionaryAPI>({\n data: apiResult,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type AddDictionaryBody = DictionaryCreationData;\nexport type AddDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Adds a new dictionary to the database.\n */\nexport const addDictionary = async (\n req: Request<any, any, AddDictionaryBody>,\n res: ResponseWithInformation<AddDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const dictionaryData = req.body;\n\n if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryData.projectIds.includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_PROJECT_MISMATCH');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n const dictionary: DictionaryData = {\n key: dictionaryData.key,\n title: dictionaryData.title,\n description: dictionaryData.description,\n content: {\n v1: {\n content: dictionaryData.content,\n },\n },\n creatorId: user._id,\n filePath: {\n [String(project._id)]: dictionaryData.filePath ?? '',\n },\n projectIds: dictionaryData.projectIds ?? [String(project._id)],\n };\n\n try {\n const newDictionary = await dictionaryService.createDictionary(dictionary);\n\n const apiResult = mapDictionaryToAPI(newDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary created successfully',\n fr: 'Dictionnaire créé avec succès',\n es: 'Diccionario creado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been created successfully',\n fr: 'Votre dictionnaire a été créé avec succès',\n es: 'Su diccionario ha sido creado con éxito',\n }),\n data: apiResult,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type PushDictionariesBody = {\n dictionaries: LocalDictionary[];\n};\ntype PushDictionariesResultData = {\n newDictionaries: string[];\n updatedDictionaries: string[];\n error: { dictionaryId: string; message: string }[];\n};\nexport type PushDictionariesResult = ResponseData<PushDictionariesResultData>;\n\n/**\n * Check each dictionaries, add the new ones and update the existing ones.\n * @param req - Express request object.\n * @param res - Express response object.\n * @returns Response containing the created dictionary.\n */\nexport const pushDictionaries = async (\n req: Request<any, any, PushDictionariesBody>,\n res: ResponseWithInformation<PushDictionariesResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const dictionaryData = req.body.dictionaries;\n const dictionariesKeys = dictionaryData.map((dictionary) => dictionary.key);\n\n if (\n typeof dictionaryData === 'object' &&\n Array.isArray(dictionaryData) &&\n dictionaryData.length === 0\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARIES_NOT_PROVIDED');\n return;\n } else if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryRights?.write) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_WRITE');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n try {\n const { existingDictionariesKey, newDictionariesKey } =\n await dictionaryService.getExistingDictionaryKey(\n dictionariesKeys,\n project._id\n );\n\n const existingDictionaries = dictionaryData.filter((dictionary) =>\n existingDictionariesKey.includes(dictionary.key)\n );\n const newDictionaries = dictionaryData.filter((dictionary) =>\n newDictionariesKey.includes(dictionary.key)\n );\n\n const result: PushDictionariesResultData = {\n newDictionaries: [],\n updatedDictionaries: [],\n error: [],\n };\n\n for (const dictionaryDataEl of newDictionaries) {\n const publishedVersion = dictionaryDataEl.publishedVersion\n ? dictionaryDataEl.publishedVersion === '-1'\n ? null\n : dictionaryDataEl.publishedVersion\n : null;\n\n const dictionary: DictionaryData = {\n title: dictionaryDataEl.title,\n description: dictionaryDataEl.description,\n projectIds: [String(project._id)],\n creatorId: user._id,\n content: {\n v1: {\n content: dictionaryDataEl.content,\n },\n },\n filePath: {\n [String(project._id)]: dictionaryDataEl.filePath ?? '',\n },\n key: dictionaryDataEl.key,\n publishedVersion,\n };\n\n try {\n const newDictionary =\n await dictionaryService.createDictionary(dictionary);\n result.newDictionaries.push(newDictionary.key);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n }\n\n if (existingDictionariesKey.length >= 0) {\n const existingDictionariesDB =\n await dictionaryService.getDictionariesByKeys(\n existingDictionariesKey,\n project._id\n );\n\n for (const dictionaryDataEl of existingDictionaries) {\n const existingDictionaryDB = existingDictionariesDB.find(\n (dictionaryDB) => dictionaryDB.key === dictionaryDataEl.key\n )!;\n\n const existingContentArray = Object.values(\n existingDictionaryDB.content\n );\n\n const lastContent =\n existingContentArray[existingContentArray.length - 1].content;\n\n const isSameContent =\n JSON.stringify(lastContent) ===\n JSON.stringify(dictionaryDataEl.content);\n\n let newContent: VersionedContent = existingDictionaryDB.content;\n\n if (!isSameContent) {\n const newContentVersion =\n dictionaryService.incrementVersion(existingDictionaryDB);\n\n newContent = {\n ...newContent,\n [newContentVersion]: {\n content: dictionaryDataEl.content,\n },\n };\n }\n\n const publishedVersion = dictionaryDataEl.publishedVersion\n ? dictionaryDataEl.publishedVersion === '-1'\n ? null\n : dictionaryDataEl.publishedVersion\n : null;\n\n const dictionary: DictionaryData = {\n ...existingDictionaryDB,\n ...dictionaryDataEl,\n content: newContent,\n projectIds: [String(project._id)],\n creatorId: user._id,\n filePath: {\n [String(project._id)]: dictionaryDataEl.filePath ?? '',\n },\n publishedVersion,\n key: dictionaryDataEl.key,\n };\n\n try {\n const newDictionary = await dictionaryService.updateDictionaryByKey(\n dictionaryDataEl.key,\n dictionary,\n project._id\n );\n result.updatedDictionaries.push(newDictionary.key);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n }\n }\n\n const responseData = formatResponse<PushDictionariesResultData>({\n message: t({\n en: 'Dictionaries updated successfully',\n fr: 'Dictionnaires mis à jour avec succès',\n es: 'Diccionarios actualizados con éxito',\n }),\n description: t({\n en: 'Your dictionaries have been updated successfully',\n fr: 'Vos dictionnaires ont été mis à jour avec succès',\n es: 'Sus diccionarios han sido actualizados con éxito',\n }),\n data: result,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type UpdateDictionaryParam = { dictionaryId: string };\nexport type UpdateDictionaryBody = Partial<Dictionary>;\nexport type UpdateDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Updates an existing dictionary in the database.\n */\nexport const updateDictionary = async (\n req: Request<UpdateDictionaryParam, any, UpdateDictionaryBody>,\n res: ResponseWithInformation<UpdateDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { dictionaryId } = req.params;\n const { project, dictionaryRights } = res.locals;\n const dictionaryData = req.body;\n\n if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryData.projectIds?.includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_PROJECT_MISMATCH');\n return;\n }\n\n if (typeof dictionaryId === 'undefined') {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_ID_NOT_FOUND');\n return;\n }\n\n if (!dictionaryRights?.write) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_WRITE');\n return;\n }\n\n try {\n const updatedDictionary = await dictionaryService.updateDictionaryById(\n dictionaryId,\n dictionaryData\n );\n\n const apiResult = mapDictionaryToAPI(updatedDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary updated successfully',\n fr: 'Dictionnaire mis à jour avec succès',\n es: 'Diccionario actualizado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been updated successfully',\n fr: 'Votre dictionnaire a été mis à jour avec succès',\n es: 'Su diccionario ha sido actualizado con éxito',\n }),\n data: apiResult,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type DeleteDictionaryParam = { dictionaryId: string };\nexport type DeleteDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Deletes a dictionary from the database by its ID.\n */\nexport const deleteDictionary = async (\n req: Request<DeleteDictionaryParam>,\n res: ResponseWithInformation<DeleteDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, dictionaryRights } = res.locals;\n const { dictionaryId } = req.params as Partial<DeleteDictionaryParam>;\n\n if (!dictionaryId) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_ID_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n try {\n const dictionaryToDelete =\n await dictionaryService.getDictionaryById(dictionaryId);\n\n if (!dictionaryToDelete.projectIds.includes(project._id)) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'DICTIONARY_PROJECT_MISMATCH'\n );\n return;\n }\n\n const deletedDictionary =\n await dictionaryService.deleteDictionaryById(dictionaryId);\n\n if (!deletedDictionary) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_NOT_FOUND', {\n dictionaryId,\n });\n return;\n }\n\n logger.info(`Dictionary deleted: ${String(deletedDictionary._id)}`);\n\n const apiResult = mapDictionaryToAPI(deletedDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary deleted successfully',\n fr: 'Dictionnaire supprimé avec succès',\n es: 'Diccionario eliminado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been deleted successfully',\n fr: 'Votre dictionnaire a été supprimé avec succès',\n es: 'Su diccionario ha sido eliminado con éxito',\n }),\n data: apiResult,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":"AAEA,SAAS,cAAc;AAEvB,YAAY,uBAAuB;AACnC,SAAmB,oBAAoB;AACvC;AAAA,EAEE;AAAA,OACK;AAEP,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EAGA;AAAA,OACK;AAEP,SAAS,SAAS;AAgBX,MAAM,kBAAkB,OAC7B,KACA,KACA,UACkB;AAClB,QAAM,EAAE,MAAM,SAAS,iBAAiB,IAAI,IAAI;AAChD,QAAM,EAAE,SAAS,UAAU,MAAM,MAAM,iBAAiB,IACtD,kCAAkC,GAAG;AAEvC,MAAI,CAAC,SAAS;AACZ,iBAAa,2BAA2B,KAAK,qBAAqB;AAClE;AAAA,EACF;AACA,MAAI,CAAC,MAAM;AACT,iB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nE,UAAM,eAAe,eAA8B;AAAA,MACjD,SAAS,EAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,aAAa,EAAE;AAAA,QACb,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,MAAM;AAAA,IACR,CAAC;AAED,QAAI,KAAK,YAAY;AACrB;AAAA,EACF,SAAS,OAAO;AACd,iBAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/dictionary.controller.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { type Dictionary as LocalDictionary } from '@intlayer/core';\nimport { logger } from '@logger';\nimport type { ResponseWithInformation } from '@middlewares/sessionAuth.middleware';\nimport * as dictionaryService from '@services/dictionary.service';\nimport { AppError, ErrorHandler } from '@utils/errors';\nimport {\n type DictionaryFiltersParams,\n getDictionaryFiltersAndPagination,\n} from '@utils/filtersAndPagination/getDictionaryFiltersAndPagination';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport { mapDictionaryToAPI } from '@utils/mapper/dictionary';\nimport {\n formatPaginatedResponse,\n type ResponseData,\n type PaginatedResponse,\n formatResponse,\n} from '@utils/responseData';\nimport type { NextFunction, Request } from 'express';\nimport { t } from 'express-intlayer';\nimport * as eventListener from '@/controllers/event-listener';\nimport type {\n Dictionary,\n DictionaryAPI,\n DictionaryCreationData,\n DictionaryData,\n VersionedContent,\n} from '@/types/dictionary.types';\n\nexport type GetDictionariesParams =\n FiltersAndPagination<DictionaryFiltersParams>;\nexport type GetDictionariesResult = PaginatedResponse<DictionaryAPI>;\n\n/**\n * Retrieves a list of dictionaries based on filters and pagination.\n */\nexport const getDictionaries = async (\n req: Request<GetDictionariesParams>,\n res: ResponseWithInformation<GetDictionariesResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, project, dictionaryRights } = res.locals;\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getDictionaryFiltersAndPagination(req);\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionaries = await dictionaryService.findDictionaries(\n filters,\n skip,\n pageSize\n );\n const totalItems = await dictionaryService.countDictionaries(filters);\n\n const dictionariesAPI = dictionaries.map((el) =>\n mapDictionaryToAPI(el, project._id, el.publishedVersion ?? undefined)\n );\n\n const responseData = formatPaginatedResponse<DictionaryAPI>({\n data: dictionariesAPI,\n page,\n pageSize,\n totalPages: getNumberOfPages(totalItems),\n totalItems,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetDictionariesKeysResult = ResponseData<string[]>;\n\n/**\n * Retrieves a list of dictionaries keys based on filters and pagination.\n */\nexport const getDictionariesKeys = async (\n _req: Request,\n res: ResponseWithInformation<GetDictionariesKeysResult>,\n _next: NextFunction\n) => {\n const { project, dictionaryRights } = res.locals;\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionariesKeys = await dictionaryService.getDictionariesKeys(\n project._id\n );\n\n const responseData = formatResponse<string[]>({\n data: dictionariesKeys,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetDictionaryParams = { dictionaryKey: string };\nexport type GetDictionaryQuery = { version?: string };\nexport type GetDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Retrieves a list of dictionaries based on filters and pagination.\n */\nexport const getDictionaryByKey = async (\n req: Request<GetDictionaryParams, any, any, GetDictionaryQuery>,\n res: ResponseWithInformation<GetDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const { dictionaryKey } = req.params;\n const version = req.query.version;\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n if (!dictionaryRights?.read) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_READ');\n return;\n }\n\n try {\n const dictionary = await dictionaryService.getDictionaryByKey(\n dictionaryKey,\n project._id\n );\n\n if (!dictionary.projectIds.map(String).includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'DICTIONARY_PROJECT_MISMATCH'\n );\n return;\n }\n\n const apiResult = mapDictionaryToAPI(dictionary, project._id, version);\n\n const responseData = formatResponse<DictionaryAPI>({\n data: apiResult,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type AddDictionaryBody = DictionaryCreationData;\nexport type AddDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Adds a new dictionary to the database.\n */\nexport const addDictionary = async (\n req: Request<any, any, AddDictionaryBody>,\n res: ResponseWithInformation<AddDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const dictionaryData = req.body;\n\n if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryData.projectIds.includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_PROJECT_MISMATCH');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n const dictionary: DictionaryData = {\n key: dictionaryData.key,\n title: dictionaryData.title,\n description: dictionaryData.description,\n content: {\n v1: {\n content: dictionaryData.content,\n },\n },\n creatorId: user._id,\n filePath: {\n [String(project._id)]: dictionaryData.filePath ?? '',\n },\n projectIds: dictionaryData.projectIds ?? [String(project._id)],\n };\n\n try {\n const newDictionary = await dictionaryService.createDictionary(dictionary);\n\n const apiResult = mapDictionaryToAPI(newDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary created successfully',\n fr: 'Dictionnaire créé avec succès',\n es: 'Diccionario creado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been created successfully',\n fr: 'Votre dictionnaire a été créé avec succès',\n es: 'Su diccionario ha sido creado con éxito',\n }),\n data: apiResult,\n });\n\n res.json(responseData);\n\n eventListener.sendDictionaryUpdate([\n {\n dictionary: mapDictionaryToAPI(newDictionary, project._id),\n status: 'ADDED',\n },\n ]);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type PushDictionariesBody = {\n dictionaries: LocalDictionary[];\n};\ntype PushDictionariesResultData = {\n newDictionaries: string[];\n updatedDictionaries: string[];\n error: { dictionaryId: string; message: string }[];\n};\nexport type PushDictionariesResult = ResponseData<PushDictionariesResultData>;\n\n/**\n * Check each dictionaries, add the new ones and update the existing ones.\n * @param req - Express request object.\n * @param res - Express response object.\n * @returns Response containing the created dictionary.\n */\nexport const pushDictionaries = async (\n req: Request<any, any, PushDictionariesBody>,\n res: ResponseWithInformation<PushDictionariesResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, user, dictionaryRights } = res.locals;\n const dictionaryData = req.body.dictionaries;\n const dictionariesKeys = dictionaryData.map((dictionary) => dictionary.key);\n\n if (\n typeof dictionaryData === 'object' &&\n Array.isArray(dictionaryData) &&\n dictionaryData.length === 0\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARIES_NOT_PROVIDED');\n return;\n } else if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryRights?.write) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_WRITE');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n try {\n const { existingDictionariesKey, newDictionariesKey } =\n await dictionaryService.getExistingDictionaryKey(\n dictionariesKeys,\n project._id\n );\n\n const existingDictionaries = dictionaryData.filter((dictionary) =>\n existingDictionariesKey.includes(dictionary.key)\n );\n const newDictionaries = dictionaryData.filter((dictionary) =>\n newDictionariesKey.includes(dictionary.key)\n );\n\n const newDictionariesResult: DictionaryAPI[] = [];\n const updatedDictionariesResult: DictionaryAPI[] = [];\n const errorResult: PushDictionariesResultData['error'] = [];\n\n for (const dictionaryDataEl of newDictionaries) {\n const publishedVersion = dictionaryDataEl.publishedVersion\n ? dictionaryDataEl.publishedVersion === '-1'\n ? null\n : dictionaryDataEl.publishedVersion\n : null;\n\n const dictionary: DictionaryData = {\n title: dictionaryDataEl.title,\n description: dictionaryDataEl.description,\n projectIds: [String(project._id)],\n creatorId: user._id,\n content: {\n v1: {\n content: dictionaryDataEl.content,\n },\n },\n filePath: {\n [String(project._id)]: dictionaryDataEl.filePath ?? '',\n },\n key: dictionaryDataEl.key,\n publishedVersion,\n };\n\n try {\n const newDictionary =\n await dictionaryService.createDictionary(dictionary);\n newDictionariesResult.push(\n mapDictionaryToAPI(newDictionary, project._id)\n );\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n }\n\n if (existingDictionariesKey.length >= 0) {\n const existingDictionariesDB =\n await dictionaryService.getDictionariesByKeys(\n existingDictionariesKey,\n project._id\n );\n\n for (const dictionaryDataEl of existingDictionaries) {\n const existingDictionaryDB = existingDictionariesDB.find(\n (dictionaryDB) => dictionaryDB.key === dictionaryDataEl.key\n )!;\n\n const existingContentArray = Object.values(\n existingDictionaryDB.content\n );\n\n const lastContent =\n existingContentArray[existingContentArray.length - 1].content;\n\n const isSameContent =\n JSON.stringify(lastContent) ===\n JSON.stringify(dictionaryDataEl.content);\n\n let newContent: VersionedContent = existingDictionaryDB.content;\n\n if (!isSameContent) {\n const newContentVersion =\n dictionaryService.incrementVersion(existingDictionaryDB);\n\n newContent = {\n ...newContent,\n [newContentVersion]: {\n content: dictionaryDataEl.content,\n },\n };\n }\n\n const publishedVersion = dictionaryDataEl.publishedVersion\n ? dictionaryDataEl.publishedVersion === '-1'\n ? null\n : dictionaryDataEl.publishedVersion\n : null;\n\n const dictionary: DictionaryData = {\n ...existingDictionaryDB,\n ...dictionaryDataEl,\n content: newContent,\n projectIds: [String(project._id)],\n creatorId: user._id,\n filePath: {\n [String(project._id)]: dictionaryDataEl.filePath ?? '',\n },\n publishedVersion,\n key: dictionaryDataEl.key,\n };\n\n try {\n const updatedDictionary =\n await dictionaryService.updateDictionaryByKey(\n dictionaryDataEl.key,\n dictionary,\n project._id\n );\n updatedDictionariesResult.push(\n mapDictionaryToAPI(updatedDictionary, project._id)\n );\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n }\n }\n\n const result: PushDictionariesResultData = {\n newDictionaries: newDictionariesResult.map(\n (dictionary) => dictionary.key\n ),\n updatedDictionaries: updatedDictionariesResult.map(\n (dictionary) => dictionary.key\n ),\n error: errorResult,\n };\n\n const responseData = formatResponse<PushDictionariesResultData>({\n message: t({\n en: 'Dictionaries updated successfully',\n fr: 'Dictionnaires mis à jour avec succès',\n es: 'Diccionarios actualizados con éxito',\n }),\n description: t({\n en: 'Your dictionaries have been updated successfully',\n fr: 'Vos dictionnaires ont été mis à jour avec succès',\n es: 'Sus diccionarios han sido actualizados con éxito',\n }),\n data: result,\n });\n\n eventListener.sendDictionaryUpdate([\n ...newDictionariesResult.map(\n (dictionary) =>\n ({\n dictionary,\n status: 'ADDED',\n }) as eventListener.SendDictionaryUpdateArg\n ),\n ...updatedDictionariesResult.map(\n (dictionary) =>\n ({\n dictionary,\n status: 'UPDATED',\n }) as eventListener.SendDictionaryUpdateArg\n ),\n ]);\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type UpdateDictionaryParam = { dictionaryId: string };\nexport type UpdateDictionaryBody = Partial<Dictionary>;\nexport type UpdateDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Updates an existing dictionary in the database.\n */\nexport const updateDictionary = async (\n req: Request<UpdateDictionaryParam, any, UpdateDictionaryBody>,\n res: ResponseWithInformation<UpdateDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { dictionaryId } = req.params;\n const { project, dictionaryRights } = res.locals;\n const dictionaryData = req.body;\n\n if (!dictionaryData) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_DATA_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryData.projectIds?.includes(String(project._id))) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_PROJECT_MISMATCH');\n return;\n }\n\n if (typeof dictionaryId === 'undefined') {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_ID_NOT_FOUND');\n return;\n }\n\n if (!dictionaryRights?.write) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_WRITE');\n return;\n }\n\n try {\n const updatedDictionary = await dictionaryService.updateDictionaryById(\n dictionaryId,\n dictionaryData\n );\n\n const apiResult = mapDictionaryToAPI(updatedDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary updated successfully',\n fr: 'Dictionnaire mis à jour avec succès',\n es: 'Diccionario actualizado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been updated successfully',\n fr: 'Votre dictionnaire a été mis à jour avec succès',\n es: 'Su diccionario ha sido actualizado con éxito',\n }),\n data: apiResult,\n });\n\n eventListener.sendDictionaryUpdate([\n {\n dictionary: apiResult,\n status: 'UPDATED',\n },\n ]);\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type DeleteDictionaryParam = { dictionaryId: string };\nexport type DeleteDictionaryResult = ResponseData<DictionaryAPI>;\n\n/**\n * Deletes a dictionary from the database by its ID.\n */\nexport const deleteDictionary = async (\n req: Request<DeleteDictionaryParam>,\n res: ResponseWithInformation<DeleteDictionaryResult>,\n _next: NextFunction\n): Promise<void> => {\n const { project, dictionaryRights } = res.locals;\n const { dictionaryId } = req.params as Partial<DeleteDictionaryParam>;\n\n if (!dictionaryId) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_ID_NOT_FOUND');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!dictionaryRights?.admin) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_RIGHTS_NOT_ADMIN');\n return;\n }\n\n try {\n const dictionaryToDelete =\n await dictionaryService.getDictionaryById(dictionaryId);\n\n if (!dictionaryToDelete.projectIds.includes(project._id)) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'DICTIONARY_PROJECT_MISMATCH'\n );\n return;\n }\n\n const deletedDictionary =\n await dictionaryService.deleteDictionaryById(dictionaryId);\n\n if (!deletedDictionary) {\n ErrorHandler.handleGenericErrorResponse(res, 'DICTIONARY_NOT_FOUND', {\n dictionaryId,\n });\n return;\n }\n\n logger.info(`Dictionary deleted: ${String(deletedDictionary._id)}`);\n\n const apiResult = mapDictionaryToAPI(deletedDictionary, project._id);\n\n const responseData = formatResponse<DictionaryAPI>({\n message: t({\n en: 'Dictionary deleted successfully',\n fr: 'Dictionnaire supprimé avec succès',\n es: 'Diccionario eliminado con éxito',\n }),\n description: t({\n en: 'Your dictionary has been deleted successfully',\n fr: 'Votre dictionnaire a été supprimé avec succès',\n es: 'Su diccionario ha sido eliminado con éxito',\n }),\n data: apiResult,\n });\n\n res.json(responseData);\n\n eventListener.sendDictionaryUpdate([\n {\n dictionary: apiResult,\n status: 'DELETED',\n },\n ]);\n\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":"AAEA,SAAS,cAAc;AAEvB,YAAY,uBAAuB;AACnC,SAAmB,oBAAoB;AACvC;AAAA,EAEE;AAAA,OACK;AAEP,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EAGA;AAAA,OACK;AAEP,SAAS,SAAS;AAClB,YAAY,mBAAmB;AAgBxB,MAAM,kBAAkB,OAC7B,KACA,KACA,UACkB;AAClB,QAAM,EAAE,MAAM,SAAS,iBAAiB,IAAI,IAAI;AAChD,QAAM,EAAE,SAAS,UAAU,MAAM,MAAM,iBAAiB,IACtD,kCAAkC,GAAG;AAEvC,MAAI,CAAC,SAAS;AACZ,iBAAa,2BAA2B,KAAK,qBAAqB;AAClE;AAAA,EACF;AACA,MAAI,CAAC,MAAM;AACT,iBAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AACA,MAAI,CAAC,kBAAkB,MAAM;AAC3B,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,SAAS;AACZ,iBAAa,2BAA2B,KAAK,qBAAqB;AAClE;AAAA,EACF;AAEA,MAAI,CAAC,kBAAkB,OAAO;AAC5B,iBAAa,2BAA2B,KAAK,6BAA6B;AAC1E;AAAA,EACF;AAEA,MAAI;AACF,UAAM,qBACJ,MAAM,kBAAkB,kBAAkB,YAAY;AAExD,QAAI,CAAC,mBAAmB,WAAW,SAAS,QAAQ,GAAG,GAAG;AACxD,mBAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAEA,UAAM,oBACJ,MAAM,kBAAkB,qBAAqB,YAAY;AAE3D,QAAI,CAAC,mBAAmB;AACtB,mBAAa,2BAA2B,KAAK,wBAAwB;AAAA,QACnE;AAAA,MACF,CAAC;AACD;AAAA,IACF;AAEA,WAAO,KAAK,uBAAuB,OAAO,kBAAkB,GAAG,CAAC,EAAE;AAElE,UAAM,YAAY,mBAAmB,mBAAmB,QAAQ,GAAG;AAEnE,UAAM,eAAe,eAA8B;AAAA,MACjD,SAAS,EAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,aAAa,EAAE;AAAA,QACb,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,MAAM;AAAA,IACR,CAAC;AAED,QAAI,KAAK,YAAY;AAErB,kBAAc,qBAAqB;AAAA,MACjC;AAAA,QACE,YAAY;AAAA,QACZ,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAED;AAAA,EACF,SAAS,OAAO;AACd,iBAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as oAuth2Service from "./../services/oAuth2.service.mjs";
|
|
2
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
3
|
+
let clients = [];
|
|
4
|
+
const sendDictionaryUpdate = (args) => {
|
|
5
|
+
const projectIds = args.flatMap((arg) => arg.dictionary.projectIds);
|
|
6
|
+
const filteredClients = clients.filter(
|
|
7
|
+
(client) => projectIds.map((id) => String(id)).includes(String(client.projectId))
|
|
8
|
+
);
|
|
9
|
+
for (const client of filteredClients) {
|
|
10
|
+
client.res.write(`data: ${JSON.stringify(args)}
|
|
11
|
+
|
|
12
|
+
`);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const listenChangeSSE = async (req, res) => {
|
|
16
|
+
const { accessToken } = req.params;
|
|
17
|
+
if (!accessToken) {
|
|
18
|
+
ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_AUTHENTICATED");
|
|
19
|
+
}
|
|
20
|
+
const tokenInformation = await oAuth2Service.getAccessToken(accessToken);
|
|
21
|
+
if (!tokenInformation) {
|
|
22
|
+
ErrorHandler.handleGenericErrorResponse(res, "AUTH_ERROR");
|
|
23
|
+
}
|
|
24
|
+
res.setHeader("Content-Type", "text/event-stream;charset=utf-8");
|
|
25
|
+
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
26
|
+
res.setHeader("Connection", "keep-alive");
|
|
27
|
+
res.setHeader("X-Accel-Buffering", "no");
|
|
28
|
+
res.write(":\n\n");
|
|
29
|
+
res.flushHeaders();
|
|
30
|
+
const clientId = Date.now();
|
|
31
|
+
const newClient = {
|
|
32
|
+
id: clientId,
|
|
33
|
+
projectId: String(tokenInformation.project._id),
|
|
34
|
+
res
|
|
35
|
+
};
|
|
36
|
+
clients.push(newClient);
|
|
37
|
+
req.on("close", () => {
|
|
38
|
+
clients = clients.filter((client) => client.id !== clientId);
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
export {
|
|
42
|
+
listenChangeSSE,
|
|
43
|
+
sendDictionaryUpdate
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=event-listener.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/event-listener.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ResponseWithInformation } from '@middlewares/sessionAuth.middleware';\nimport { Token } from '@schemas/oAuth2.schema';\nimport * as oAuth2Service from '@services/oAuth2.service';\nimport { ErrorHandler } from '@utils/errors';\nimport { Response, Request } from 'express';\nimport { DictionaryAPI } from '@/types/dictionary.types';\n\nlet clients: Array<{ id: number; projectId: string; res: Response }> = [];\n\nexport type SendDictionaryUpdateArg = {\n dictionary: DictionaryAPI;\n status: 'ADDED' | 'UPDATED' | 'DELETED' | 'CREATED';\n};\n\nexport const sendDictionaryUpdate = (args: SendDictionaryUpdateArg[]) => {\n const projectIds = args.flatMap((arg) => arg.dictionary.projectIds);\n\n const filteredClients = clients.filter((client) =>\n projectIds.map((id) => String(id)).includes(String(client.projectId))\n );\n\n for (const client of filteredClients) {\n client.res.write(`data: ${JSON.stringify(args)}\\n\\n`);\n }\n};\n\nexport type CheckDictionaryChangeSSEParams = { accessToken: string };\n\n/**\n * SSE to check the email verification status\n */\nexport const listenChangeSSE = async (\n req: Request<CheckDictionaryChangeSSEParams, any, any>,\n res: ResponseWithInformation\n) => {\n const { accessToken } = req.params;\n\n if (!accessToken) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_AUTHENTICATED');\n }\n\n const tokenInformation = await oAuth2Service.getAccessToken(accessToken);\n\n if (!tokenInformation) {\n ErrorHandler.handleGenericErrorResponse(res, 'AUTH_ERROR');\n }\n\n // Set headers for SSE\n res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');\n res.setHeader('Cache-Control', 'no-cache, no-transform');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no'); // For Nginx buffering\n\n // Send initial data to ensure the connection is open\n res.write(':\\n\\n'); // Comment to keep connection alive\n res.flushHeaders();\n\n const clientId = Date.now();\n\n // Add client to the list\n const newClient = {\n id: clientId,\n projectId: String((tokenInformation as unknown as Token).project._id),\n res,\n };\n clients.push(newClient);\n\n // Remove client on connection close\n req.on('close', () => {\n clients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sources":["../../../src/controllers/oAuth2.controller.ts"],"sourcesContent":["import { RequestWithOAuth2Information } from '@middlewares/oAuth2.middleware';\nimport { AppError, ErrorHandler } from '@utils/errors';\nimport { formatResponse, ResponseData } from '@utils/responseData';\nimport { Response, Request, NextFunction } from 'express';\nimport {\n
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/oAuth2.controller.ts"],"sourcesContent":["import { RequestWithOAuth2Information } from '@middlewares/oAuth2.middleware';\nimport { AppError, ErrorHandler } from '@utils/errors';\nimport { formatResponse, ResponseData } from '@utils/responseData';\nimport { Response, Request, NextFunction } from 'express';\nimport {\n Request as OAuthRequest,\n Response as OAuthResponse,\n} from 'oauth2-server';\nimport { OAuth2Token } from '@/types/oAuth2.types';\n\nexport type GetOAuth2TokenBody = {\n grant_type: 'client_credentials';\n client_id: string;\n client_secret: string;\n};\nexport type GetOAuth2TokenResult = ResponseData<OAuth2Token>;\n\n// Method to get the token\nexport const getOAuth2Token = async (\n req: Request,\n res: Response<GetOAuth2TokenResult>,\n _next: NextFunction\n): Promise<void> => {\n const oauthRequest = new OAuthRequest(req);\n const oauthResponse = new OAuthResponse(res);\n\n try {\n const token: OAuth2Token = (await (\n req as unknown as RequestWithOAuth2Information<\n undefined,\n undefined,\n GetOAuth2TokenBody\n >\n ).oauth.token(oauthRequest, oauthResponse)) as OAuth2Token;\n\n const responseData = formatResponse<OAuth2Token>({\n data: token,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":"AACA,SAAmB,oBAAoB;AACvC,SAAS,sBAAoC;AAE7C;AAAA,EACE,WAAW;AAAA,EACX,YAAY;AAAA,OACP;AAWA,MAAM,iBAAiB,OAC5B,KACA,KACA,UACkB;AAClB,QAAM,eAAe,IAAI,aAAa,GAAG;AACzC,QAAM,gBAAgB,IAAI,cAAc,GAAG;AAE3C,MAAI;AACF,UAAM,QAAsB,MAC1B,IAKA,MAAM,MAAM,cAAc,aAAa;AAEzC,UAAM,eAAe,eAA4B;AAAA,MAC/C,MAAM;AAAA,IACR,CAAC;AAED,QAAI,KAAK,YAAY;AACrB;AAAA,EACF,SAAS,OAAO;AACd,iBAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
@@ -3,7 +3,7 @@ import { sessionAuthRoutes } from "./../routes/sessionAuth.routes.mjs";
|
|
|
3
3
|
import { sendEmail } from "./../services/email.service.mjs";
|
|
4
4
|
import * as sessionAuthService from "./../services/sessionAuth.service.mjs";
|
|
5
5
|
import * as userService from "./../services/user.service.mjs";
|
|
6
|
-
import { ErrorHandler } from "./../utils/errors
|
|
6
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
7
7
|
import {
|
|
8
8
|
getOrganizationFiltersAndPagination
|
|
9
9
|
} from "./../utils/filtersAndPagination/getOrganizationFiltersAndPagination.mjs";
|
|
@@ -2,7 +2,7 @@ import { logger } from "./../logger/index.mjs";
|
|
|
2
2
|
import * as projectService from "./../services/project.service.mjs";
|
|
3
3
|
import * as sessionAuthService from "./../services/sessionAuth.service.mjs";
|
|
4
4
|
import * as userService from "./../services/user.service.mjs";
|
|
5
|
-
import { ErrorHandler } from "./../utils/errors
|
|
5
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
6
6
|
import {
|
|
7
7
|
getProjectFiltersAndPagination
|
|
8
8
|
} from "./../utils/filtersAndPagination/getProjectFiltersAndPagination.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as projectAccessKeyService from "./../services/projectAccessKey.service.mjs";
|
|
2
|
-
import { ErrorHandler } from "./../utils/errors
|
|
2
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
3
3
|
import { formatResponse } from "./../utils/responseData.mjs";
|
|
4
4
|
import { t } from "express-intlayer";
|
|
5
5
|
const addNewAccessKey = async (req, res, _next) => {
|
|
@@ -5,7 +5,7 @@ import { sendEmail } from "./../services/email.service.mjs";
|
|
|
5
5
|
import * as sessionAuthService from "./../services/sessionAuth.service.mjs";
|
|
6
6
|
import * as userService from "./../services/user.service.mjs";
|
|
7
7
|
import { generateToken } from "./../utils/CSRF.mjs";
|
|
8
|
-
import { ErrorHandler, GenericError } from "./../utils/errors
|
|
8
|
+
import { ErrorHandler, GenericError } from "./../utils/errors.mjs";
|
|
9
9
|
import { HttpStatusCodes } from "./../utils/httpStatusCodes.mjs";
|
|
10
10
|
import { mapOrganizationToAPI } from "./../utils/mapper/organization.mjs";
|
|
11
11
|
import { mapProjectToAPI } from "./../utils/mapper/project.mjs";
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import * as subscriptionService from "./../services/subscription.service.mjs";
|
|
2
|
-
import { ErrorHandler } from "./../utils/errors
|
|
2
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
3
3
|
import { retrievePlanInformation } from "./../utils/plan.mjs";
|
|
4
4
|
import { formatResponse } from "./../utils/responseData.mjs";
|
|
5
5
|
import { t } from "express-intlayer";
|
|
6
6
|
import { Stripe } from "stripe";
|
|
7
|
-
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
|
8
7
|
const getSubscription = async (req, res) => {
|
|
9
8
|
try {
|
|
9
|
+
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
|
10
10
|
const { organization, user } = res.locals;
|
|
11
11
|
const { priceId } = req.body;
|
|
12
12
|
if (!organization) {
|
|
@@ -93,6 +93,7 @@ const getSubscription = async (req, res) => {
|
|
|
93
93
|
}
|
|
94
94
|
};
|
|
95
95
|
const cancelSubscription = async (_req, res) => {
|
|
96
|
+
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
|
96
97
|
try {
|
|
97
98
|
const { organization, user } = res.locals;
|
|
98
99
|
if (!organization) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/stripe.controller.ts"],"sourcesContent":["import { ResponseWithInformation } from '@middlewares/sessionAuth.middleware';\nimport * as subscriptionService from '@services/subscription.service';\nimport { ErrorHandler, AppError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport { formatResponse, ResponseData } from '@utils/responseData';\nimport { Request } from 'express';\nimport { t } from 'express-intlayer';\nimport { Locales } from 'intlayer';\nimport { Stripe } from 'stripe';\nimport type { Organization } from '@/types/organization.types';\n\nconst stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\nexport type GetCheckoutSessionBody = {\n organizationId: string;\n priceId: string;\n};\n\ntype CheckoutSessionData = {\n subscriptionId: string;\n clientSecret: string;\n status: Stripe.Subscription.Status;\n};\n\nexport type GetCheckoutSessionResult = ResponseData<CheckoutSessionData>;\n\n/**\n * Handles subscription creation or update with Stripe and returns a ClientSecret.\n * @param req - Express request object.\n * @param res - Express response object.\n */\nexport const getSubscription = async (\n req: Request<undefined, undefined, GetCheckoutSessionBody>,\n res: ResponseWithInformation<GetCheckoutSessionResult>\n): Promise<void> => {\n try {\n // Extract organization and user from response locals (set by authentication middleware)\n const { organization, user } = res.locals;\n // Get the price ID (Stripe Price ID) from the request body\n const { priceId } = req.body;\n\n // Validate that the organization exists\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_FOUND');\n return;\n }\n\n // Validate that the user exists\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_FOUND');\n return;\n }\n\n // Ensure the user is a member of the organization\n if (!organization.membersIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_MEMBER'\n );\n return;\n }\n\n // Ensure the user is an admin of the organization\n if (!organization.adminsIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_ADMIN'\n );\n return;\n }\n\n const { period, type } = retrievePlanInformation(priceId);\n\n if (\n organization.plan?.subscriptionId ||\n (organization.plan?.type === type && organization.plan?.period === period)\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'ALREADY_SUBSCRIBED', {\n organizationId: organization._id,\n });\n return;\n }\n\n // Attempt to retrieve the Stripe customer ID from the organization's plan\n let customerId = organization.plan?.customerId;\n\n if (!customerId) {\n // If no customer ID exists, create a new Stripe customer for the organization\n const customer = await stripe.customers.create({\n metadata: {\n organizationId: String(organization._id),\n userId: String(user._id),\n // Include the locale for potential localization\n locale: (res.locals as unknown as { locale: Locales }).locale,\n },\n });\n customerId = customer.id;\n }\n\n // If no subscription exists, create a new one\n const subscription = await stripe.subscriptions.create({\n customer: customerId, // Associate the subscription with the customer\n items: [{ price: priceId }], // Set the price ID for the subscription\n expand: ['latest_invoice.payment_intent'], // Expand to get payment intent details\n payment_settings: {\n payment_method_types: ['card'], // Specify payment method types\n },\n payment_behavior: 'default_incomplete', // Create the subscription in an incomplete state until payment is confirmed\n });\n\n // Handle subscription creation failure\n if (!subscription) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'SUBSCRIPTION_CREATION_FAILED',\n {\n user,\n organization,\n priceId,\n }\n );\n return;\n }\n\n // Prepare the response data with subscription details\n const responseData = formatResponse<CheckoutSessionData>({\n data: {\n subscriptionId: subscription.id,\n // Retrieve the client secret from the payment intent to complete payment on the client side\n clientSecret:\n (\n (subscription.latest_invoice as Stripe.Invoice)\n .payment_intent as Stripe.PaymentIntent\n )?.client_secret ?? '',\n status: subscription.status, // Subscription status (e.g., 'incomplete', 'active')\n },\n });\n\n // Send the response back to the client\n res.json(responseData);\n\n return;\n } catch (error) {\n // Handle any errors that occur during the process\n\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\ntype CancelSubscriptionData = Organization['plan'];\n\ntype CancelSubscriptionResult = ResponseData<CancelSubscriptionData>;\n\n/**\n * Cancels a subscription for an organization.\n * @param _req - Express request object.\n * @param res - Express response object.\n */\nexport const cancelSubscription = async (\n _req: Request,\n res: ResponseWithInformation<CancelSubscriptionResult>\n): Promise<void> => {\n try {\n // Extract the organization and user from the response locals\n // These are typically set by authentication middleware earlier in the request pipeline\n const { organization, user } = res.locals;\n\n // Validate that the organization exists\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_FOUND');\n return;\n }\n\n // Validate that the user exists\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_FOUND');\n return;\n }\n\n // Check if the user is an admin of the organization\n if (!organization.adminsIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_ADMIN'\n );\n return;\n }\n\n // Check if the organization has an active subscription to cancel\n if (!organization.plan?.subscriptionId) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'ORGANIZATION_PLAN_NOT_FOUND'\n );\n return;\n }\n\n // Cancel the subscription on Stripe immediately using the subscription ID\n await stripe.subscriptions.cancel(organization.plan.subscriptionId);\n\n // Update the organization's plan in the database to reflect the cancellation\n const plan = await subscriptionService.cancelSubscription(\n organization.plan.subscriptionId,\n String(organization._id)\n );\n\n // If the plan could not be updated in the database, handle the error\n if (!plan) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'ORGANIZATION_PLAN_NOT_FOUND'\n );\n return;\n }\n\n // Prepare a formatted response with a success message and the updated plan data\n const formattedPlan = formatResponse<CancelSubscriptionData>({\n message: t({\n en: 'Subscription cancelled successfully',\n fr: 'Souscription annulée avec succès',\n es: 'Suscripción cancelada con éxito',\n }),\n description: t({\n en: 'Your subscription has been cancelled successfully',\n fr: 'Votre souscription a été annulée avec succès',\n es: 'Su suscripción ha sido cancelada con éxito',\n }),\n data: plan!,\n });\n\n // Send the response back to the client\n res.json(formattedPlan);\n } catch (error) {\n // Handle any errors that occur during the cancellation process\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n }\n};\n"],"mappings":"AACA,YAAY,yBAAyB;AACrC,SAAS,oBAA8B;AACvC,SAAS,+BAA+B;AACxC,SAAS,sBAAoC;AAE7C,SAAS,SAAS;AAElB,SAAS,cA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MAClB,OAAO,aAAa,GAAG;AAAA,IACzB;AAGA,QAAI,CAAC,MAAM;AACT,mBAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAGA,UAAM,gBAAgB,eAAuC;AAAA,MAC3D,SAAS,EAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,aAAa,EAAE;AAAA,QACb,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,MAAM;AAAA,IACR,CAAC;AAGD,QAAI,KAAK,aAAa;AAAA,EACxB,SAAS,OAAO;AAEd,iBAAa,uBAAuB,KAAK,KAAiB;AAAA,EAC5D;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/stripe.controller.ts"],"sourcesContent":["import { ResponseWithInformation } from '@middlewares/sessionAuth.middleware';\nimport * as subscriptionService from '@services/subscription.service';\nimport { ErrorHandler, AppError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport { formatResponse, ResponseData } from '@utils/responseData';\nimport { Request } from 'express';\nimport { t } from 'express-intlayer';\nimport { Locales } from 'intlayer';\nimport { Stripe } from 'stripe';\nimport type { Organization } from '@/types/organization.types';\n\nexport type GetCheckoutSessionBody = {\n organizationId: string;\n priceId: string;\n};\n\ntype CheckoutSessionData = {\n subscriptionId: string;\n clientSecret: string;\n status: Stripe.Subscription.Status;\n};\n\nexport type GetCheckoutSessionResult = ResponseData<CheckoutSessionData>;\n\n/**\n * Handles subscription creation or update with Stripe and returns a ClientSecret.\n * @param req - Express request object.\n * @param res - Express response object.\n */\nexport const getSubscription = async (\n req: Request<undefined, undefined, GetCheckoutSessionBody>,\n res: ResponseWithInformation<GetCheckoutSessionResult>\n): Promise<void> => {\n try {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n // Extract organization and user from response locals (set by authentication middleware)\n const { organization, user } = res.locals;\n // Get the price ID (Stripe Price ID) from the request body\n const { priceId } = req.body;\n\n // Validate that the organization exists\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_FOUND');\n return;\n }\n\n // Validate that the user exists\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_FOUND');\n return;\n }\n\n // Ensure the user is a member of the organization\n if (!organization.membersIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_MEMBER'\n );\n return;\n }\n\n // Ensure the user is an admin of the organization\n if (!organization.adminsIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_ADMIN'\n );\n return;\n }\n\n const { period, type } = retrievePlanInformation(priceId);\n\n if (\n organization.plan?.subscriptionId ||\n (organization.plan?.type === type && organization.plan?.period === period)\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'ALREADY_SUBSCRIBED', {\n organizationId: organization._id,\n });\n return;\n }\n\n // Attempt to retrieve the Stripe customer ID from the organization's plan\n let customerId = organization.plan?.customerId;\n\n if (!customerId) {\n // If no customer ID exists, create a new Stripe customer for the organization\n const customer = await stripe.customers.create({\n metadata: {\n organizationId: String(organization._id),\n userId: String(user._id),\n // Include the locale for potential localization\n locale: (res.locals as unknown as { locale: Locales }).locale,\n },\n });\n customerId = customer.id;\n }\n\n // If no subscription exists, create a new one\n const subscription = await stripe.subscriptions.create({\n customer: customerId, // Associate the subscription with the customer\n items: [{ price: priceId }], // Set the price ID for the subscription\n expand: ['latest_invoice.payment_intent'], // Expand to get payment intent details\n payment_settings: {\n payment_method_types: ['card'], // Specify payment method types\n },\n payment_behavior: 'default_incomplete', // Create the subscription in an incomplete state until payment is confirmed\n });\n\n // Handle subscription creation failure\n if (!subscription) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'SUBSCRIPTION_CREATION_FAILED',\n {\n user,\n organization,\n priceId,\n }\n );\n return;\n }\n\n // Prepare the response data with subscription details\n const responseData = formatResponse<CheckoutSessionData>({\n data: {\n subscriptionId: subscription.id,\n // Retrieve the client secret from the payment intent to complete payment on the client side\n clientSecret:\n (\n (subscription.latest_invoice as Stripe.Invoice)\n .payment_intent as Stripe.PaymentIntent\n )?.client_secret ?? '',\n status: subscription.status, // Subscription status (e.g., 'incomplete', 'active')\n },\n });\n\n // Send the response back to the client\n res.json(responseData);\n\n return;\n } catch (error) {\n // Handle any errors that occur during the process\n\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\ntype CancelSubscriptionData = Organization['plan'];\n\ntype CancelSubscriptionResult = ResponseData<CancelSubscriptionData>;\n\n/**\n * Cancels a subscription for an organization.\n * @param _req - Express request object.\n * @param res - Express response object.\n */\nexport const cancelSubscription = async (\n _req: Request,\n res: ResponseWithInformation<CancelSubscriptionResult>\n): Promise<void> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // Extract the organization and user from the response locals\n // These are typically set by authentication middleware earlier in the request pipeline\n const { organization, user } = res.locals;\n\n // Validate that the organization exists\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_FOUND');\n return;\n }\n\n // Validate that the user exists\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_FOUND');\n return;\n }\n\n // Check if the user is an admin of the organization\n if (!organization.adminsIds.map(String).includes(String(user._id))) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'USER_NOT_ORGANIZATION_ADMIN'\n );\n return;\n }\n\n // Check if the organization has an active subscription to cancel\n if (!organization.plan?.subscriptionId) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'ORGANIZATION_PLAN_NOT_FOUND'\n );\n return;\n }\n\n // Cancel the subscription on Stripe immediately using the subscription ID\n await stripe.subscriptions.cancel(organization.plan.subscriptionId);\n\n // Update the organization's plan in the database to reflect the cancellation\n const plan = await subscriptionService.cancelSubscription(\n organization.plan.subscriptionId,\n String(organization._id)\n );\n\n // If the plan could not be updated in the database, handle the error\n if (!plan) {\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'ORGANIZATION_PLAN_NOT_FOUND'\n );\n return;\n }\n\n // Prepare a formatted response with a success message and the updated plan data\n const formattedPlan = formatResponse<CancelSubscriptionData>({\n message: t({\n en: 'Subscription cancelled successfully',\n fr: 'Souscription annulée avec succès',\n es: 'Suscripción cancelada con éxito',\n }),\n description: t({\n en: 'Your subscription has been cancelled successfully',\n fr: 'Votre souscription a été annulée avec succès',\n es: 'Su suscripción ha sido cancelada con éxito',\n }),\n data: plan!,\n });\n\n // Send the response back to the client\n res.json(formattedPlan);\n } catch (error) {\n // Handle any errors that occur during the cancellation process\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n }\n};\n"],"mappings":"AACA,YAAY,yBAAyB;AACrC,SAAS,oBAA8B;AACvC,SAAS,+BAA+B;AACxC,SAAS,sBAAoC;AAE7C,SAAS,SAAS;AAElB,SAAS,cAAc;AAqBhB,MAAM,kBAAkB,OAC7B,KACA,QACkB;AAClB,MAAI;AACF,UAAM,SAAS,IAAI,OAAO,QAAQ,IAAI,iBAAkB;AAGxD,UAAM,EAAE,cAAc,KAAK,IAAI,IAAI;AAEnC,UAAM,EAAE,QAAQ,IAAI,IAAI;AAGxB,QAAI,CAAC,cAAc;AACjB,mBAAa,2BAA2B,KAAK,wBAAwB;AACrE;AAAA,IACF;AAGA,QAAI,CAAC,MAAM;AACT,mBAAa,2BAA2B,KAAK,gBAAgB;AAC7D;AAAA,IACF;AAGA,QAAI,CAAC,aAAa,WAAW,IAAI,MAAM,EAAE,SAAS,OAAO,KAAK,GAAG,CAAC,GAAG;AACnE,mBAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAGA,QAAI,CAAC,aAAa,UAAU,IAAI,MAAM,EAAE,SAAS,OAAO,KAAK,GAAG,CAAC,GAAG;AAClE,mBAAa;AAAA,QACX;AAAA,QACA;A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from "./../services/tag.service.mjs";
|
|
3
|
-
import { ErrorHandler } from "./../utils/errors
|
|
3
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
4
4
|
import {
|
|
5
5
|
getTagFiltersAndPagination
|
|
6
6
|
} from "./../utils/filtersAndPagination/getTagFiltersAndPagination.mjs";
|
|
@@ -2,7 +2,7 @@ import { logger } from "./../logger/index.mjs";
|
|
|
2
2
|
import { sessionAuthRoutes } from "./../routes/sessionAuth.routes.mjs";
|
|
3
3
|
import { sendEmail } from "./../services/email.service.mjs";
|
|
4
4
|
import * as userService from "./../services/user.service.mjs";
|
|
5
|
-
import { ErrorHandler } from "./../utils/errors
|
|
5
|
+
import { ErrorHandler } from "./../utils/errors.mjs";
|
|
6
6
|
import { getOrganizationFiltersAndPagination } from "./../utils/filtersAndPagination/getOrganizationFiltersAndPagination.mjs";
|
|
7
7
|
import { mapUsersToAPI, mapUserToAPI } from "./../utils/mapper/user.mjs";
|
|
8
8
|
import {
|
package/dist/esm/index.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { sessionAuthRouter } from "./routes/sessionAuth.routes.mjs";
|
|
|
24
24
|
import { userRouter } from "./routes/user.routes.mjs";
|
|
25
25
|
import { stripeRouter } from "./routes/stripe.routes.mjs";
|
|
26
26
|
import { aiRouter } from "./routes/ai.routes.mjs";
|
|
27
|
+
import { eventListenerRouter } from "./routes/event-listener.routes.mjs";
|
|
27
28
|
import { stripeWebhook } from "./webhooks/stripe.webhook.mjs";
|
|
28
29
|
import { getOAuth2Token } from "./controllers/oAuth2.controller.mjs";
|
|
29
30
|
import {
|
|
@@ -32,13 +33,15 @@ import {
|
|
|
32
33
|
} from "./controllers/sessionAuth.controller.mjs";
|
|
33
34
|
import { doubleCsrfProtection } from "./utils/CSRF.mjs";
|
|
34
35
|
import { connectDB } from "./utils/mongoDB/connectDB.mjs";
|
|
35
|
-
import { logger } from "./logger
|
|
36
|
+
import { logger } from "./logger.mjs";
|
|
36
37
|
const app = express();
|
|
37
38
|
app.disable("x-powered-by");
|
|
38
39
|
app.use(helmet());
|
|
39
40
|
const env = app.get("env");
|
|
40
41
|
logger.info(`run as ${env}`);
|
|
41
|
-
dotenv.config({
|
|
42
|
+
dotenv.config({
|
|
43
|
+
path: [`.env.${env}.local`, `.env.${env}`, ".env.local", ".env"]
|
|
44
|
+
});
|
|
42
45
|
app.use(cookieParser());
|
|
43
46
|
app.use(intlayer());
|
|
44
47
|
const isDev = env === "development";
|
|
@@ -51,10 +54,8 @@ app.post(
|
|
|
51
54
|
app.use(compression());
|
|
52
55
|
app.use(express.json({ limit: "50mb" }));
|
|
53
56
|
app.use(express.urlencoded({ extended: true }));
|
|
54
|
-
const whitelist = [process.env.CLIENT_URL];
|
|
55
57
|
const corsOptions = {
|
|
56
|
-
origin:
|
|
57
|
-
credentials: true,
|
|
58
|
+
origin: "*",
|
|
58
59
|
allowedHeaders: [
|
|
59
60
|
"authorization",
|
|
60
61
|
"Content-Type",
|
|
@@ -70,7 +71,6 @@ const corsOptions = {
|
|
|
70
71
|
methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
|
|
71
72
|
};
|
|
72
73
|
app.use(cors(corsOptions));
|
|
73
|
-
logger.info("url whitelist : ", whitelist.join(", "));
|
|
74
74
|
app.get("/", (_req, res) => {
|
|
75
75
|
res.send(
|
|
76
76
|
t({
|
|
@@ -115,6 +115,7 @@ app.use("/api/tag", tagRouter);
|
|
|
115
115
|
app.use("/api/dictionary", dictionaryRouter);
|
|
116
116
|
app.use("/api/stripe", stripeRouter);
|
|
117
117
|
app.use("/api/ai", aiRouter);
|
|
118
|
+
app.use("/api/event-listener", eventListenerRouter);
|
|
118
119
|
app.listen(process.env.PORT, () => {
|
|
119
120
|
logger.info(`Listening on port ${process.env.PORT}`);
|
|
120
121
|
});
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* eslint-disable import/order */\n\n// Libraries\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport cors, { type CorsOptions } from 'cors';\nimport dotenv from 'dotenv';\nimport express, { type Express } from 'express';\nimport { intlayer, t } from 'express-intlayer';\nimport helmet from 'helmet';\n\n// Middlewares\nimport {\n attachOAuthInstance,\n authenticateOAuth2,\n RequestWithOAuth2Information,\n} from '@middlewares/oAuth2.middleware';\nimport { logAPIRequestURL } from '@middlewares/request.middleware';\nimport {\n checkUser,\n checkOrganization,\n checkProject,\n checkAdmin,\n ResponseWithInformation,\n} from '@middlewares/sessionAuth.middleware';\n\n// Routes\nimport { dictionaryRouter } from '@routes/dictionary.routes';\nimport { organizationRouter } from '@routes/organization.routes';\nimport { projectRouter } from '@routes/project.routes';\nimport { tagRouter } from '@routes/tags.routes';\nimport { sessionAuthRouter } from '@routes/sessionAuth.routes';\nimport { userRouter } from '@routes/user.routes';\nimport { stripeRouter } from '@routes/stripe.routes';\nimport { aiRouter } from '@routes/ai.routes';\n\n// Webhooks\nimport { stripeWebhook } from '@webhooks/stripe.webhook';\n\n// Controllers\nimport { getOAuth2Token } from '@controllers/oAuth2.controller';\nimport {\n getSessionInformation,\n setCSRFToken,\n} from '@controllers/sessionAuth.controller';\n\n// Utils\nimport { doubleCsrfProtection } from '@utils/CSRF';\nimport { connectDB } from '@utils/mongoDB/connectDB';\n\n// Logger\nimport { logger } from './logger';\n\nconst app: Express = express();\n\napp.disable('x-powered-by'); // Disabled to prevent attackers from knowing that the app is running Express\napp.use(helmet());\n\n// Environment variables\nconst env = app.get('env');\n\nlogger.info(`run as ${env}`);\n\ndotenv.config({
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* eslint-disable import/order */\n\n// Libraries\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport cors, { type CorsOptions } from 'cors';\nimport dotenv from 'dotenv';\nimport express, { type Express } from 'express';\nimport { intlayer, t } from 'express-intlayer';\nimport helmet from 'helmet';\n\n// Middlewares\nimport {\n attachOAuthInstance,\n authenticateOAuth2,\n RequestWithOAuth2Information,\n} from '@middlewares/oAuth2.middleware';\nimport { logAPIRequestURL } from '@middlewares/request.middleware';\nimport {\n checkUser,\n checkOrganization,\n checkProject,\n checkAdmin,\n ResponseWithInformation,\n} from '@middlewares/sessionAuth.middleware';\n\n// Routes\nimport { dictionaryRouter } from '@routes/dictionary.routes';\nimport { organizationRouter } from '@routes/organization.routes';\nimport { projectRouter } from '@routes/project.routes';\nimport { tagRouter } from '@routes/tags.routes';\nimport { sessionAuthRouter } from '@routes/sessionAuth.routes';\nimport { userRouter } from '@routes/user.routes';\nimport { stripeRouter } from '@routes/stripe.routes';\nimport { aiRouter } from '@routes/ai.routes';\nimport { eventListenerRouter } from '@routes/event-listener.routes';\n\n// Webhooks\nimport { stripeWebhook } from '@webhooks/stripe.webhook';\n\n// Controllers\nimport { getOAuth2Token } from '@controllers/oAuth2.controller';\nimport {\n getSessionInformation,\n setCSRFToken,\n} from '@controllers/sessionAuth.controller';\n\n// Utils\nimport { doubleCsrfProtection } from '@utils/CSRF';\nimport { connectDB } from '@utils/mongoDB/connectDB';\n\n// Logger\nimport { logger } from './logger';\n\nconst app: Express = express();\n\napp.disable('x-powered-by'); // Disabled to prevent attackers from knowing that the app is running Express\napp.use(helmet());\n\n// Environment variables\nconst env = app.get('env');\n\nlogger.info(`run as ${env}`);\n\ndotenv.config({\n path: [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'],\n});\n\n// Parse incoming requests with cookies\napp.use(cookieParser());\n\n// Load internationalization request handler\napp.use(intlayer());\n\nconst isDev = env === 'development';\n\n// Connect to MongoDB\nconnectDB();\n\n// Stripe\napp.post(\n '/webhook/stripe',\n express.raw({ type: 'application/json' }),\n stripeWebhook\n);\n\n// Compress all HTTP responses\napp.use(compression());\n\n// Parse incoming requests with JSON payloads\napp.use(express.json({ limit: '50mb' }));\n\n// Parse incoming requests with urlencoded payloads\napp.use(express.urlencoded({ extended: true }));\n\n// CORS\nconst corsOptions: CorsOptions = {\n origin: '*',\n allowedHeaders: [\n 'authorization',\n 'Content-Type',\n 'credentials',\n 'cache-control',\n 'Access-Control-Allow-Origin',\n 'private-state-token-redemption',\n 'private-state-token-issuance',\n 'browsing-topics',\n ],\n\n exposedHeaders: [''],\n preflightContinue: false,\n methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',\n};\napp.use(cors(corsOptions));\n\n// Liveness check\napp.get('/', (_req, res) => {\n res.send(\n t({\n en: 'Ok - locale: en',\n fr: 'Ok - locale: fr',\n es: 'Ok - locale: es',\n })\n );\n});\n\n// middleware - jwt & session auth\napp.use(/(.*)/, checkUser);\napp.use(/(.*)/, checkOrganization);\napp.use(/(.*)/, checkProject);\napp.use(/(.*)/, checkAdmin);\n\n// debug\nif (isDev) {\n app.use(logAPIRequestURL);\n}\n\n// Sessions\napp.get('/session', getSessionInformation);\napp.use('/api/auth', sessionAuthRouter);\n\n// CSRF\napp.get('/csrf-token', setCSRFToken);\n\n// oAuth2\napp.use(/(.*)/, attachOAuthInstance);\napp.post('/oauth2/token', getOAuth2Token); // Route to get the token\napp.use(/(.*)/, (req, res, next) => {\n // If the request is not already authenticated check the oAuth2 token\n if (!res.locals.authType) {\n return authenticateOAuth2(\n req as RequestWithOAuth2Information,\n res as ResponseWithInformation,\n next\n );\n }\n next();\n});\n\n// CSRF protection\napp.use(/(.*)/, (req, res, next) => {\n // If the request is authenticated using the session auth check the CSRF token\n if (res.locals.authType === 'session') {\n return doubleCsrfProtection(req, res, next);\n }\n next();\n});\n\n// Routes\napp.use('/api/user', userRouter);\napp.use('/api/organization', organizationRouter);\napp.use('/api/project', projectRouter);\napp.use('/api/tag', tagRouter);\napp.use('/api/dictionary', dictionaryRouter);\napp.use('/api/stripe', stripeRouter);\napp.use('/api/ai', aiRouter);\napp.use('/api/event-listener', eventListenerRouter);\n\n// Server\napp.listen(process.env.PORT, () => {\n logger.info(`Listening on port ${process.env.PORT}`);\n});\n\n// Export tu use as serverless function\nexport default app;\n"],"mappings":"A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mBAAmB,gBAAgB;AAC3C,IAAI,IAAI,eAAe,YAAY;AACnC,IAAI,IAAI,WAAW,QAAQ;AAC3B,IAAI,IAAI,uBAAuB,mBAAmB;AAGlD,IAAI,OAAO,QAAQ,IAAI,MAAM,MAAM;AACjC,SAAO,KAAK,qBAAqB,QAAQ,IAAI,IAAI,EAAE;AACrD,CAAC;AAGD,IAAO,gBAAQ;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { listenChangeSSE } from "./../controllers/event-listener.mjs";
|
|
2
|
+
import { Router } from "express";
|
|
3
|
+
const eventListenerRouter = Router();
|
|
4
|
+
const baseURL = `${process.env.BACKEND_URL}/api/event-listener`;
|
|
5
|
+
const eventListenerRoutes = {
|
|
6
|
+
checkDictionaryChangeSSE: {
|
|
7
|
+
urlModel: "/:accessToken",
|
|
8
|
+
url: ({ accessToken }) => `${baseURL}/${accessToken}`,
|
|
9
|
+
method: "GET"
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
eventListenerRouter.get(
|
|
13
|
+
eventListenerRoutes.checkDictionaryChangeSSE.urlModel,
|
|
14
|
+
listenChangeSSE
|
|
15
|
+
);
|
|
16
|
+
export {
|
|
17
|
+
eventListenerRouter,
|
|
18
|
+
eventListenerRoutes
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=event-listener.routes.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/event-listener.routes.ts"],"sourcesContent":["import { listenChangeSSE } from '@controllers/event-listener';\nimport { Router } from 'express';\nimport { Routes } from '@/types/Routes';\n\nexport const eventListenerRouter: Router = Router();\n\nconst baseURL = `${process.env.BACKEND_URL}/api/event-listener`;\n\nexport const eventListenerRoutes = {\n checkDictionaryChangeSSE: {\n urlModel: '/:accessToken',\n url: ({ accessToken }: { accessToken: string }) =>\n `${baseURL}/${accessToken}`,\n method: 'GET',\n },\n} satisfies Routes;\n\neventListenerRouter.get(\n eventListenerRoutes.checkDictionaryChangeSSE.urlModel,\n listenChangeSSE\n);\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAGhB,MAAM,sBAA8B,OAAO;AAElD,MAAM,UAAU,GAAG,QAAQ,IAAI,WAAW;AAEnC,MAAM,sBAAsB;AAAA,EACjC,0BAA0B;AAAA,IACxB,UAAU;AAAA,IACV,KAAK,CAAC,EAAE,YAAY,MAClB,GAAG,OAAO,IAAI,WAAW;AAAA,IAC3B,QAAQ;AAAA,EACV;AACF;AAEA,oBAAoB;AAAA,EAClB,oBAAoB,yBAAyB;AAAA,EAC7C;AACF;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DictionaryModel } from "./../models/dictionary.model.mjs";
|
|
2
2
|
import { ensureMongoDocumentToObject } from "./../utils/ensureMongoDocumentToObject.mjs";
|
|
3
|
-
import { GenericError } from "./../utils/errors
|
|
3
|
+
import { GenericError } from "./../utils/errors.mjs";
|
|
4
4
|
import { removeObjectKeys } from "./../utils/removeObjectKeys.mjs";
|
|
5
5
|
import {
|
|
6
6
|
validateDictionary
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { randomBytes } from "crypto";
|
|
2
2
|
import { OAuth2AccessTokenModel } from "./../models/oAuth2.model.mjs";
|
|
3
3
|
import { ProjectModel } from "./../models/project.model.mjs";
|
|
4
|
-
import { GenericError } from "./../utils/errors
|
|
4
|
+
import { GenericError } from "./../utils/errors.mjs";
|
|
5
|
+
import { mapOrganizationToAPI } from "./../utils/mapper/organization.mjs";
|
|
6
|
+
import { mapProjectToAPI } from "./../utils/mapper/project.mjs";
|
|
7
|
+
import { mapUserToAPI } from "./../utils/mapper/user.mjs";
|
|
5
8
|
import { getTokenExpireAt } from "./../utils/oAuth2.mjs";
|
|
6
9
|
import { getOrganizationById } from "./organization.service.mjs";
|
|
7
10
|
import { getUserById } from "./user.service.mjs";
|
|
@@ -55,9 +58,9 @@ const formatOAuth2Token = (token, client, user, project, organization, rights) =
|
|
|
55
58
|
const formattedToken = {
|
|
56
59
|
...restToken,
|
|
57
60
|
client,
|
|
58
|
-
user,
|
|
59
|
-
organization,
|
|
60
|
-
project,
|
|
61
|
+
user: mapUserToAPI(user),
|
|
62
|
+
organization: mapOrganizationToAPI(organization, false),
|
|
63
|
+
project: mapProjectToAPI(project, user, false),
|
|
61
64
|
accessToken: token.accessToken,
|
|
62
65
|
accessTokenExpiresAt: token.accessTokenExpiresAt ?? /* @__PURE__ */ new Date("999-99-99"),
|
|
63
66
|
rights
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/oAuth2.service.ts"],"sourcesContent":["import { randomBytes } from 'crypto';\nimport { OAuth2AccessTokenModel } from '@models/oAuth2.model';\nimport { ProjectModel } from '@models/project.model';\nimport { GenericError } from '@utils/errors';\nimport { getTokenExpireAt } from '@utils/oAuth2';\nimport { Client, User, Token as OAuth2Token, Callback } from 'oauth2-server';\nimport { Token } from '../schemas/oAuth2.schema';\nimport { getOrganizationById } from './organization.service';\nimport { getUserById } from './user.service';\nimport { UserDocument } from '@/export';\nimport { Organization } from '@/types/organization.types';\nimport { OAuth2Access, Project, ProjectDocument } from '@/types/project.types';\n\n/**\n * Function to generate client credentials\n *\n * @returns The client id and client secret\n */\nexport const generateClientCredentials = (): {\n clientId: string;\n clientSecret: string;\n} => {\n const clientId = randomBytes(16).toString('hex'); // Generate a 16 character hexadecimal string\n const clientSecret = randomBytes(32).toString('hex'); // Generate a 32 character hexadecimal string\n\n return { clientId, clientSecret };\n};\n\n/**\n * Method to get the client and the project\n *\n * @param clientId - The client id\n * @param clientSecret - The client secret\n * @returns The an object containing the client, the rights and the project or false if not found\n */\nexport const getClientAndProjectByClientId = async (\n clientId: string\n): Promise<\n | {\n client: Client;\n oAuth2Access: OAuth2Access;\n project: ProjectDocument;\n rights: Token['rights'];\n }\n | false\n> => {\n const project = await ProjectModel.findOne({\n 'oAuth2Access.clientId': clientId,\n });\n\n if (!project) {\n return false;\n }\n\n const oAuth2Access = project.oAuth2Access.find(\n (access) => access.clientId === clientId\n );\n\n if (!oAuth2Access) {\n return false;\n }\n\n const formattedClient: Client = {\n id: oAuth2Access.clientId,\n clientId,\n clientSecret: oAuth2Access.clientSecret,\n grants: ['client_credentials'],\n };\n\n return {\n client: formattedClient,\n oAuth2Access,\n rights: oAuth2Access.rights,\n project,\n };\n};\n\n/**\n * Get the client and verify that the client secret is correct\n *\n * @param clientId - The client id\n * @param clientSecret - The client secret\n * @returns The client or false if not found\n */\nexport const getClient = async (\n clientId: string,\n clientSecret: string\n): Promise<Client | false> => {\n const result = await getClientAndProjectByClientId(clientId);\n\n if (!result) {\n return false;\n }\n\n const { client } = result;\n\n if (!client || client.clientSecret !== clientSecret) {\n return false;\n }\n\n return client;\n};\n\n/**\n * Format an OAuth2Token\n *\n * @param token\n * @param client\n * @param user\n * @param project\n * @param organization\n * @returns\n */\nexport const formatOAuth2Token = (\n token: Token,\n client: Client,\n user: User,\n project: Project,\n organization: Organization,\n rights: Token['rights']\n): OAuth2Token => {\n const { clientId, userId, ...restToken } = token;\n\n if (String(userId) !== String(user._id)) {\n throw new GenericError('USER_ID_MISMATCH');\n }\n\n const formattedToken: OAuth2Token = {\n ...restToken,\n client,\n user,\n organization,\n project,\n accessToken: token.accessToken,\n accessTokenExpiresAt: token.accessTokenExpiresAt ?? new Date('999-99-99'),\n rights,\n };\n\n return formattedToken;\n};\n\n/**\n * Format a auth token for the database\n *\n * @param token - The oAuth2 token to format\n * @param clientId - The client ID\n * @param userId - The user ID\n * @returns\n */\nexport const formatDBToken = (\n token: OAuth2Token,\n clientId: Client['id'],\n userId: User['_id']\n): Token => {\n const formattedToken: Token = {\n clientId: clientId,\n userId: userId,\n accessToken: token.accessToken,\n expiresIn: token.accessTokenExpiresAt ?? getTokenExpireAt(),\n };\n\n return formattedToken;\n};\n\n/**\n * Method to save the token\n *\n * @param token - The token\n * @param client - The client\n * @param user - The user\n * @returns The saved token or false if not saved\n */\nexport const saveToken = async (\n token: OAuth2Token,\n client: Client,\n user: User\n): Promise<OAuth2Token | false> => {\n const formattedAccessToken: Token = formatDBToken(token, client.id, user._id);\n\n const result = await OAuth2AccessTokenModel.create(formattedAccessToken);\n\n if (!result) {\n return false;\n }\n\n const result2 = await getClientAndProjectByClientId(result.clientId);\n\n if (!result2) {\n return false;\n }\n\n const { project } = result2;\n\n const organization = await getOrganizationById(project.organizationId);\n\n if (!organization) {\n return false;\n }\n\n const formattedResult = formatOAuth2Token(\n formattedAccessToken,\n client,\n user,\n project,\n organization,\n token.rights\n );\n return formattedResult;\n};\n\n/**\n * Method to get the access token\n *\n * @param accessToken - The access token\n * @returns The access token or false if not found\n */\nexport const getAccessToken = async (\n accessToken: string\n): Promise<OAuth2Token | false> => {\n const token = await OAuth2AccessTokenModel.findOne({\n accessToken,\n });\n\n if (!token) {\n return false;\n }\n\n const { userId, clientId } = token;\n\n const user = await getUserById(userId);\n\n if (!user) {\n return false;\n }\n\n const result = await getClientAndProjectByClientId(clientId);\n\n if (!result) {\n return false;\n }\n\n const { client, project, rights } = result;\n\n const organization = await getOrganizationById(project.organizationId);\n\n if (!organization) {\n return false;\n }\n\n const formattedAccessToken = formatOAuth2Token(\n token,\n client,\n user,\n project,\n organization,\n rights\n );\n\n return formattedAccessToken;\n};\n\n/**\n * Method to get the user from the client\n *\n * @param client - The client\n * @returns The user or false if not found\n */\nexport const getUserFromClient = async (\n client: Client\n): Promise<UserDocument | false> => {\n const response = await getClientAndProjectByClientId(client.id);\n\n if (!response) {\n return false;\n }\n\n const { userId } = response.oAuth2Access;\n\n if (!userId) {\n return false;\n }\n\n const user = await getUserById(userId);\n\n return user ?? false;\n};\n\n/**\n * Method to verify the permissions (grants)\n *\n * @param token - The token\n * @param scope - The scope\n * @returns True if the token has the required scope, false otherwise\n */\nexport const verifyScope = async (\n _token: OAuth2Token,\n _scope: string,\n _callback?: Callback<boolean> | undefined\n): Promise<boolean> => {\n // Implement the verification of scopes if necessary\n return true;\n};\n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,MAAM,8BAA8B,QAAQ;AAE3D,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,EAAE,QAAQ,SAAS,OAAO,IAAI;AAEpC,QAAM,eAAe,MAAM,oBAAoB,QAAQ,cAAc;AAErE,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,uBAAuB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO;AACT;AAQO,MAAM,oBAAoB,OAC/B,WACkC;AAClC,QAAM,WAAW,MAAM,8BAA8B,OAAO,EAAE;AAE9D,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AAEA,QAAM,EAAE,OAAO,IAAI,SAAS;AAE5B,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,MAAM,YAAY,MAAM;AAErC,SAAO,QAAQ;AACjB;AASO,MAAM,cAAc,OACzB,QACA,QACA,cACqB;AAErB,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/oAuth2.service.ts"],"sourcesContent":["import { randomBytes } from 'crypto';\nimport { OAuth2AccessTokenModel } from '@models/oAuth2.model';\nimport { ProjectModel } from '@models/project.model';\nimport { GenericError } from '@utils/errors';\nimport { mapOrganizationToAPI } from '@utils/mapper/organization';\nimport { mapProjectToAPI } from '@utils/mapper/project';\nimport { mapUserToAPI } from '@utils/mapper/user';\nimport { getTokenExpireAt } from '@utils/oAuth2';\nimport type { Client, Callback } from 'oauth2-server';\nimport type { Token } from '../schemas/oAuth2.schema';\nimport { getOrganizationById } from './organization.service';\nimport { getUserById } from './user.service';\nimport type { OAuth2Token } from '@/types/oAuth2.types';\nimport type { Organization } from '@/types/organization.types';\nimport type {\n OAuth2Access,\n Project,\n ProjectDocument,\n} from '@/types/project.types';\nimport type { User, UserDocument } from '@/types/user.types';\n\n/**\n * Function to generate client credentials\n *\n * @returns The client id and client secret\n */\nexport const generateClientCredentials = (): {\n clientId: string;\n clientSecret: string;\n} => {\n const clientId = randomBytes(16).toString('hex'); // Generate a 16 character hexadecimal string\n const clientSecret = randomBytes(32).toString('hex'); // Generate a 32 character hexadecimal string\n\n return { clientId, clientSecret };\n};\n\n/**\n * Method to get the client and the project\n *\n * @param clientId - The client id\n * @param clientSecret - The client secret\n * @returns The an object containing the client, the rights and the project or false if not found\n */\nexport const getClientAndProjectByClientId = async (\n clientId: string\n): Promise<\n | {\n client: Client;\n oAuth2Access: OAuth2Access;\n project: ProjectDocument;\n rights: Token['rights'];\n }\n | false\n> => {\n const project = await ProjectModel.findOne({\n 'oAuth2Access.clientId': clientId,\n });\n\n if (!project) {\n return false;\n }\n\n const oAuth2Access = project.oAuth2Access.find(\n (access) => access.clientId === clientId\n );\n\n if (!oAuth2Access) {\n return false;\n }\n\n const formattedClient: Client = {\n id: oAuth2Access.clientId,\n clientId,\n clientSecret: oAuth2Access.clientSecret,\n grants: ['client_credentials'],\n };\n\n return {\n client: formattedClient,\n oAuth2Access,\n rights: oAuth2Access.rights,\n project,\n };\n};\n\n/**\n * Get the client and verify that the client secret is correct\n *\n * @param clientId - The client id\n * @param clientSecret - The client secret\n * @returns The client or false if not found\n */\nexport const getClient = async (\n clientId: string,\n clientSecret: string\n): Promise<Client | false> => {\n const result = await getClientAndProjectByClientId(clientId);\n\n if (!result) {\n return false;\n }\n\n const { client } = result;\n\n if (!client || client.clientSecret !== clientSecret) {\n return false;\n }\n\n return client;\n};\n\n/**\n * Format an OAuth2Token\n *\n * @param token\n * @param client\n * @param user\n * @param project\n * @param organization\n * @returns\n */\nexport const formatOAuth2Token = (\n token: Token,\n client: Client,\n user: User,\n project: Project,\n organization: Organization,\n rights: Token['rights']\n): OAuth2Token => {\n const { clientId, userId, ...restToken } = token;\n\n if (String(userId) !== String(user._id)) {\n throw new GenericError('USER_ID_MISMATCH');\n }\n\n const formattedToken: OAuth2Token = {\n ...restToken,\n client,\n user: mapUserToAPI(user),\n organization: mapOrganizationToAPI(organization, false),\n project: mapProjectToAPI(project, user, false),\n accessToken: token.accessToken,\n accessTokenExpiresAt: token.accessTokenExpiresAt ?? new Date('999-99-99'),\n rights,\n };\n\n return formattedToken;\n};\n\n/**\n * Format a auth token for the database\n *\n * @param token - The oAuth2 token to format\n * @param clientId - The client ID\n * @param userId - The user ID\n * @returns\n */\nexport const formatDBToken = (\n token: OAuth2Token,\n clientId: Client['id'],\n userId: User['_id']\n): Token => {\n const formattedToken: Token = {\n clientId: clientId,\n userId: userId,\n accessToken: token.accessToken,\n expiresIn: token.accessTokenExpiresAt ?? getTokenExpireAt(),\n };\n\n return formattedToken;\n};\n\n/**\n * Method to save the token\n *\n * @param token - The token\n * @param client - The client\n * @param user - The user\n * @returns The saved token or false if not saved\n */\nexport const saveToken = async (\n token: OAuth2Token,\n client: Client,\n user: User\n): Promise<OAuth2Token | false> => {\n const formattedAccessToken: Token = formatDBToken(token, client.id, user._id);\n\n const result = await OAuth2AccessTokenModel.create(formattedAccessToken);\n\n if (!result) {\n return false;\n }\n\n const result2 = await getClientAndProjectByClientId(result.clientId);\n\n if (!result2) {\n return false;\n }\n\n const { project } = result2;\n\n const organization = await getOrganizationById(project.organizationId);\n\n if (!organization) {\n return false;\n }\n\n const formattedResult = formatOAuth2Token(\n formattedAccessToken,\n client,\n user,\n project,\n organization,\n token.rights\n );\n return formattedResult;\n};\n\n/**\n * Method to get the access token\n *\n * @param accessToken - The access token\n * @returns The access token or false if not found\n */\nexport const getAccessToken = async (\n accessToken: string\n): Promise<OAuth2Token | false> => {\n const token = await OAuth2AccessTokenModel.findOne({\n accessToken,\n });\n\n if (!token) {\n return false;\n }\n\n const { userId, clientId } = token;\n\n const user = await getUserById(userId);\n\n if (!user) {\n return false;\n }\n\n const result = await getClientAndProjectByClientId(clientId);\n\n if (!result) {\n return false;\n }\n\n const { client, project, rights } = result;\n\n const organization = await getOrganizationById(project.organizationId);\n\n if (!organization) {\n return false;\n }\n\n const formattedAccessToken = formatOAuth2Token(\n token,\n client,\n user,\n project,\n organization,\n rights\n );\n\n return formattedAccessToken;\n};\n\n/**\n * Method to get the user from the client\n *\n * @param client - The client\n * @returns The user or false if not found\n */\nexport const getUserFromClient = async (\n client: Client\n): Promise<UserDocument | false> => {\n const response = await getClientAndProjectByClientId(client.id);\n\n if (!response) {\n return false;\n }\n\n const { userId } = response.oAuth2Access;\n\n if (!userId) {\n return false;\n }\n\n const user = await getUserById(userId);\n\n return user ?? false;\n};\n\n/**\n * Method to verify the permissions (grants)\n *\n * @param token - The token\n * @param scope - The scope\n * @returns True if the token has the required scope, false otherwise\n */\nexport const verifyScope = async (\n _token: OAuth2Token,\n _scope: string,\n _callback?: Callback<boolean> | undefined\n): Promise<boolean> => {\n // Implement the verification of scopes if necessary\n return true;\n};\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AAGjC,SAAS,2BAA2B;AACpC,SAAS,mBAAmB;AAerB,MAAM,4BAA4B,MAGpC;AACH,QAAM,WAAW,YAAY,EAAE,EAAE,SAAS,KAAK;AAC/C,QAAM,eAAe,YAAY,EAAE,EAAE,SAAS,KAAK;AAEnD,SAAO,EAAE,UAAU,aAAa;AAClC;AASO,MAAM,gCAAgC,OAC3C,aASG;AACH,QAAM,UAAU,MAAM,aAAa,QAAQ;AAAA,IACzC,yBAAyB;AAAA,EAC3B,CAAC;AAED,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,eAAe,QAAQ,aAAa;AAAA,IACxC,CAAC,WAAW,OAAO,aAAa;AAAA,EAClC;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,kBAA0B;AAAA,IAC9B,IAAI,aAAa;AAAA,IACjB;AAAA,IACA,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;AACjB;AASO,MAAM,cAAc,OACzB,QACA,QACA,cACqB;AAErB,SAAO;AACT;","names":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrganizationModel } from "./../models/organization.model.mjs";
|
|
2
|
-
import { GenericError } from "./../utils/errors
|
|
2
|
+
import { GenericError } from "./../utils/errors.mjs";
|
|
3
3
|
import {
|
|
4
4
|
validateOrganization
|
|
5
5
|
} from "./../utils/validation/validateOrganization.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProjectModel } from "./../models/project.model.mjs";
|
|
2
2
|
import { ensureMongoDocumentToObject } from "./../utils/ensureMongoDocumentToObject.mjs";
|
|
3
|
-
import { GenericError } from "./../utils/errors
|
|
3
|
+
import { GenericError } from "./../utils/errors.mjs";
|
|
4
4
|
import { removeObjectKeys } from "./../utils/removeObjectKeys.mjs";
|
|
5
5
|
import {
|
|
6
6
|
validateProject
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ProjectModel } from "./../models/project.model.mjs";
|
|
2
|
-
import { GenericError } from "./../utils/errors
|
|
2
|
+
import { GenericError } from "./../utils/errors.mjs";
|
|
3
3
|
import { generateClientCredentials } from "./oAuth2.service.mjs";
|
|
4
4
|
import { getProjectById } from "./project.service.mjs";
|
|
5
5
|
const addNewAccessKey = async (accessKeyData, projectId, user, organizationRights, projectRights, dictionaryRights) => {
|
|
@@ -102,7 +102,7 @@ const refreshAccessKey = async (clientId, projectId, userId) => {
|
|
|
102
102
|
}
|
|
103
103
|
);
|
|
104
104
|
if (result.modifiedCount === 0) {
|
|
105
|
-
throw new GenericError("
|
|
105
|
+
throw new GenericError("ACCESS_KEY_UPDATE_FAILED", {
|
|
106
106
|
clientId,
|
|
107
107
|
projectId
|
|
108
108
|
});
|