@intlayer/backend 5.7.2 → 5.7.4
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.map +1 -1
- package/dist/cjs/controllers/dictionary.controller.cjs +39 -20
- package/dist/cjs/controllers/dictionary.controller.cjs.map +1 -1
- package/dist/cjs/controllers/newsletter.controller.cjs +12 -13
- package/dist/cjs/controllers/newsletter.controller.cjs.map +1 -1
- package/dist/cjs/controllers/organization.controller.cjs +72 -53
- package/dist/cjs/controllers/organization.controller.cjs.map +1 -1
- package/dist/cjs/controllers/project.controller.cjs +48 -12
- package/dist/cjs/controllers/project.controller.cjs.map +1 -1
- package/dist/cjs/controllers/projectAccessKey.controller.cjs +30 -6
- package/dist/cjs/controllers/projectAccessKey.controller.cjs.map +1 -1
- package/dist/cjs/controllers/search.controller.cjs.map +1 -1
- package/dist/cjs/controllers/stripe.controller.cjs +15 -3
- package/dist/cjs/controllers/stripe.controller.cjs.map +1 -1
- package/dist/cjs/controllers/tag.controller.cjs +46 -17
- package/dist/cjs/controllers/tag.controller.cjs.map +1 -1
- package/dist/cjs/controllers/user.controller.cjs +19 -8
- package/dist/cjs/controllers/user.controller.cjs.map +1 -1
- package/dist/cjs/emails/OAuthTokenCreatedEmail.cjs +5 -7
- package/dist/cjs/emails/OAuthTokenCreatedEmail.cjs.map +1 -1
- package/dist/cjs/middlewares/sessionAuth.middleware.cjs.map +1 -1
- package/dist/cjs/routes/ai.routes.cjs.map +1 -1
- package/dist/cjs/routes/dictionary.routes.cjs.map +1 -1
- package/dist/cjs/routes/eventListener.routes.cjs.map +1 -1
- package/dist/cjs/routes/newsletter.routes.cjs.map +1 -1
- package/dist/cjs/routes/organization.routes.cjs.map +1 -1
- package/dist/cjs/routes/project.routes.cjs +3 -12
- package/dist/cjs/routes/project.routes.cjs.map +1 -1
- package/dist/cjs/routes/search.routes.cjs.map +1 -1
- package/dist/cjs/routes/stripe.routes.cjs.map +1 -1
- package/dist/cjs/routes/tags.routes.cjs.map +1 -1
- package/dist/cjs/routes/user.routes.cjs.map +1 -1
- package/dist/cjs/schemas/dictionary.schema.cjs +1 -1
- package/dist/cjs/schemas/dictionary.schema.cjs.map +1 -1
- package/dist/cjs/schemas/discussion.schema.cjs +1 -1
- package/dist/cjs/schemas/discussion.schema.cjs.map +1 -1
- package/dist/cjs/schemas/oAuth2.schema.cjs +1 -1
- package/dist/cjs/schemas/oAuth2.schema.cjs.map +1 -1
- package/dist/cjs/schemas/organization.schema.cjs +1 -1
- package/dist/cjs/schemas/organization.schema.cjs.map +1 -1
- package/dist/cjs/schemas/plans.schema.cjs +1 -1
- package/dist/cjs/schemas/plans.schema.cjs.map +1 -1
- package/dist/cjs/schemas/project.schema.cjs +1 -1
- package/dist/cjs/schemas/project.schema.cjs.map +1 -1
- package/dist/cjs/schemas/session.schema.cjs +1 -1
- package/dist/cjs/schemas/session.schema.cjs.map +1 -1
- package/dist/cjs/schemas/tag.schema.cjs +6 -1
- package/dist/cjs/schemas/tag.schema.cjs.map +1 -1
- package/dist/cjs/schemas/user.schema.cjs +1 -1
- package/dist/cjs/schemas/user.schema.cjs.map +1 -1
- package/dist/cjs/services/dictionary.service.cjs +0 -8
- package/dist/cjs/services/dictionary.service.cjs.map +1 -1
- package/dist/cjs/services/organization.service.cjs +0 -9
- package/dist/cjs/services/organization.service.cjs.map +1 -1
- package/dist/cjs/types/organization.types.cjs.map +1 -1
- package/dist/cjs/types/project.types.cjs.map +1 -1
- package/dist/cjs/types/tag.types.cjs.map +1 -1
- package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs +3 -0
- package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs.map +1 -1
- package/dist/cjs/utils/auth/getAuth.cjs +9 -5
- package/dist/cjs/utils/auth/getAuth.cjs.map +1 -1
- package/dist/cjs/utils/errors/errorCodes.cjs +13 -0
- package/dist/cjs/utils/errors/errorCodes.cjs.map +1 -1
- package/dist/cjs/utils/mapper/project.cjs +1 -2
- package/dist/cjs/utils/mapper/project.cjs.map +1 -1
- package/dist/cjs/utils/mapper/session.cjs +37 -0
- package/dist/cjs/utils/mapper/session.cjs.map +1 -0
- package/dist/cjs/utils/permissions.cjs +133 -38
- package/dist/cjs/utils/permissions.cjs.map +1 -1
- package/dist/cjs/utils/validation/validateArray.cjs +5 -1
- package/dist/cjs/utils/validation/validateArray.cjs.map +1 -1
- package/dist/esm/controllers/ai.controller.mjs.map +1 -1
- package/dist/esm/controllers/dictionary.controller.mjs +39 -20
- package/dist/esm/controllers/dictionary.controller.mjs.map +1 -1
- package/dist/esm/controllers/newsletter.controller.mjs +12 -13
- package/dist/esm/controllers/newsletter.controller.mjs.map +1 -1
- package/dist/esm/controllers/organization.controller.mjs +72 -53
- package/dist/esm/controllers/organization.controller.mjs.map +1 -1
- package/dist/esm/controllers/project.controller.mjs +48 -12
- package/dist/esm/controllers/project.controller.mjs.map +1 -1
- package/dist/esm/controllers/projectAccessKey.controller.mjs +31 -7
- package/dist/esm/controllers/projectAccessKey.controller.mjs.map +1 -1
- package/dist/esm/controllers/search.controller.mjs.map +1 -1
- package/dist/esm/controllers/stripe.controller.mjs +15 -3
- package/dist/esm/controllers/stripe.controller.mjs.map +1 -1
- package/dist/esm/controllers/tag.controller.mjs +46 -17
- package/dist/esm/controllers/tag.controller.mjs.map +1 -1
- package/dist/esm/controllers/user.controller.mjs +19 -8
- package/dist/esm/controllers/user.controller.mjs.map +1 -1
- package/dist/esm/emails/OAuthTokenCreatedEmail.mjs +5 -7
- package/dist/esm/emails/OAuthTokenCreatedEmail.mjs.map +1 -1
- package/dist/esm/middlewares/sessionAuth.middleware.mjs.map +1 -1
- package/dist/esm/routes/ai.routes.mjs.map +1 -1
- package/dist/esm/routes/dictionary.routes.mjs.map +1 -1
- package/dist/esm/routes/eventListener.routes.mjs.map +1 -1
- package/dist/esm/routes/newsletter.routes.mjs.map +1 -1
- package/dist/esm/routes/organization.routes.mjs.map +1 -1
- package/dist/esm/routes/project.routes.mjs +3 -12
- package/dist/esm/routes/project.routes.mjs.map +1 -1
- package/dist/esm/routes/search.routes.mjs.map +1 -1
- package/dist/esm/routes/stripe.routes.mjs.map +1 -1
- package/dist/esm/routes/tags.routes.mjs.map +1 -1
- package/dist/esm/routes/user.routes.mjs.map +1 -1
- package/dist/esm/schemas/dictionary.schema.mjs +1 -1
- package/dist/esm/schemas/dictionary.schema.mjs.map +1 -1
- package/dist/esm/schemas/discussion.schema.mjs +1 -1
- package/dist/esm/schemas/discussion.schema.mjs.map +1 -1
- package/dist/esm/schemas/oAuth2.schema.mjs +1 -1
- package/dist/esm/schemas/oAuth2.schema.mjs.map +1 -1
- package/dist/esm/schemas/organization.schema.mjs +1 -1
- package/dist/esm/schemas/organization.schema.mjs.map +1 -1
- package/dist/esm/schemas/plans.schema.mjs +1 -1
- package/dist/esm/schemas/plans.schema.mjs.map +1 -1
- package/dist/esm/schemas/project.schema.mjs +1 -1
- package/dist/esm/schemas/project.schema.mjs.map +1 -1
- package/dist/esm/schemas/session.schema.mjs +1 -1
- package/dist/esm/schemas/session.schema.mjs.map +1 -1
- package/dist/esm/schemas/tag.schema.mjs +6 -1
- package/dist/esm/schemas/tag.schema.mjs.map +1 -1
- package/dist/esm/schemas/user.schema.mjs +1 -1
- package/dist/esm/schemas/user.schema.mjs.map +1 -1
- package/dist/esm/services/dictionary.service.mjs +0 -7
- package/dist/esm/services/dictionary.service.mjs.map +1 -1
- package/dist/esm/services/organization.service.mjs +0 -9
- package/dist/esm/services/organization.service.mjs.map +1 -1
- package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs +3 -0
- package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs.map +1 -1
- package/dist/esm/utils/auth/getAuth.mjs +9 -5
- package/dist/esm/utils/auth/getAuth.mjs.map +1 -1
- package/dist/esm/utils/errors/errorCodes.mjs +13 -0
- package/dist/esm/utils/errors/errorCodes.mjs.map +1 -1
- package/dist/esm/utils/mapper/project.mjs +1 -2
- package/dist/esm/utils/mapper/project.mjs.map +1 -1
- package/dist/esm/utils/mapper/session.mjs +13 -0
- package/dist/esm/utils/mapper/session.mjs.map +1 -0
- package/dist/esm/utils/permissions.mjs +133 -38
- package/dist/esm/utils/permissions.mjs.map +1 -1
- package/dist/esm/utils/validation/validateArray.mjs +5 -1
- package/dist/esm/utils/validation/validateArray.mjs.map +1 -1
- package/dist/types/controllers/ai.controller.d.ts +10 -9
- package/dist/types/controllers/ai.controller.d.ts.map +1 -1
- package/dist/types/controllers/dictionary.controller.d.ts +9 -8
- package/dist/types/controllers/dictionary.controller.d.ts.map +1 -1
- package/dist/types/controllers/newsletter.controller.d.ts +5 -4
- package/dist/types/controllers/newsletter.controller.d.ts.map +1 -1
- package/dist/types/controllers/organization.controller.d.ts +14 -15
- package/dist/types/controllers/organization.controller.d.ts.map +1 -1
- package/dist/types/controllers/project.controller.d.ts +10 -9
- package/dist/types/controllers/project.controller.d.ts.map +1 -1
- package/dist/types/controllers/projectAccessKey.controller.d.ts +5 -4
- package/dist/types/controllers/projectAccessKey.controller.d.ts.map +1 -1
- package/dist/types/controllers/search.controller.d.ts.map +1 -1
- package/dist/types/controllers/stripe.controller.d.ts +9 -5
- package/dist/types/controllers/stripe.controller.d.ts.map +1 -1
- package/dist/types/controllers/tag.controller.d.ts +6 -5
- package/dist/types/controllers/tag.controller.d.ts.map +1 -1
- package/dist/types/controllers/user.controller.d.ts +9 -8
- package/dist/types/controllers/user.controller.d.ts.map +1 -1
- package/dist/types/emails/OAuthTokenCreatedEmail.d.ts.map +1 -1
- package/dist/types/middlewares/sessionAuth.middleware.d.ts +2 -0
- package/dist/types/middlewares/sessionAuth.middleware.d.ts.map +1 -1
- package/dist/types/schemas/tag.schema.d.ts.map +1 -1
- package/dist/types/services/dictionary.service.d.ts +0 -1
- package/dist/types/services/dictionary.service.d.ts.map +1 -1
- package/dist/types/services/organization.service.d.ts.map +1 -1
- package/dist/types/types/organization.types.d.ts +1 -3
- package/dist/types/types/organization.types.d.ts.map +1 -1
- package/dist/types/types/project.types.d.ts +1 -3
- package/dist/types/types/project.types.d.ts.map +1 -1
- package/dist/types/types/tag.types.d.ts +2 -0
- package/dist/types/types/tag.types.d.ts.map +1 -1
- package/dist/types/utils/AI/askDocQuestion/askDocQuestion.d.ts.map +1 -1
- package/dist/types/utils/auth/getAuth.d.ts +2 -2
- package/dist/types/utils/auth/getAuth.d.ts.map +1 -1
- package/dist/types/utils/errors/errorCodes.d.ts +13 -0
- package/dist/types/utils/errors/errorCodes.d.ts.map +1 -1
- package/dist/types/utils/mapper/project.d.ts.map +1 -1
- package/dist/types/utils/mapper/session.d.ts +4 -0
- package/dist/types/utils/mapper/session.d.ts.map +1 -0
- package/dist/types/utils/permissions.d.ts +83 -38
- package/dist/types/utils/permissions.d.ts.map +1 -1
- package/dist/types/utils/validation/validateArray.d.ts.map +1 -1
- package/package.json +10 -10
|
@@ -40,7 +40,8 @@ var import_permissions = require('./../utils/permissions.cjs');
|
|
|
40
40
|
var import_responseData = require('./../utils/responseData.cjs');
|
|
41
41
|
var import_express_intlayer = require("express-intlayer");
|
|
42
42
|
const addNewAccessKey = async (req, res, _next) => {
|
|
43
|
-
const { user, project, roles } = res.locals;
|
|
43
|
+
const { user, project, roles, permissions } = res.locals;
|
|
44
|
+
const { grants, name, expiresAt } = req.body;
|
|
44
45
|
if (!project) {
|
|
45
46
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PROJECT_NOT_DEFINED");
|
|
46
47
|
return;
|
|
@@ -49,13 +50,24 @@ const addNewAccessKey = async (req, res, _next) => {
|
|
|
49
50
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
|
|
50
51
|
return;
|
|
51
52
|
}
|
|
52
|
-
if (!(0, import_permissions.hasPermission)(
|
|
53
|
+
if (!(0, import_permissions.hasPermission)(
|
|
54
|
+
roles,
|
|
55
|
+
"project:write"
|
|
56
|
+
)({
|
|
57
|
+
...res.locals,
|
|
58
|
+
targetProjectIds: [project.id]
|
|
59
|
+
})) {
|
|
53
60
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
54
61
|
return;
|
|
55
62
|
}
|
|
63
|
+
const filteredPermisions = (0, import_permissions.intersectPermissions)(permissions, grants);
|
|
56
64
|
try {
|
|
57
65
|
const newAccessKey = await projectAccessKeyService.addNewAccessKey(
|
|
58
|
-
|
|
66
|
+
{
|
|
67
|
+
name,
|
|
68
|
+
expiresAt,
|
|
69
|
+
grants: filteredPermisions
|
|
70
|
+
},
|
|
59
71
|
project.id,
|
|
60
72
|
user
|
|
61
73
|
);
|
|
@@ -77,7 +89,7 @@ const addNewAccessKey = async (req, res, _next) => {
|
|
|
77
89
|
type: "oAuthTokenCreated",
|
|
78
90
|
to: user.email,
|
|
79
91
|
username: user.name,
|
|
80
|
-
applicationName: newAccessKey.clientId,
|
|
92
|
+
applicationName: newAccessKey.name ?? newAccessKey.clientId,
|
|
81
93
|
scopes: newAccessKey.grants,
|
|
82
94
|
tokenDetailsUrl: `${process.env.CLIENT_URL}/oauth2/token`,
|
|
83
95
|
securityLogUrl: `${process.env.CLIENT_URL}/security-log`,
|
|
@@ -104,7 +116,13 @@ const deleteAccessKey = async (req, res, _next) => {
|
|
|
104
116
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "CLIENT_ID_NOT_FOUND");
|
|
105
117
|
return;
|
|
106
118
|
}
|
|
107
|
-
if (!(0, import_permissions.hasPermission)(
|
|
119
|
+
if (!(0, import_permissions.hasPermission)(
|
|
120
|
+
roles,
|
|
121
|
+
"project:write"
|
|
122
|
+
)({
|
|
123
|
+
...res.locals,
|
|
124
|
+
targetProjectIds: [project.id]
|
|
125
|
+
})) {
|
|
108
126
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
109
127
|
return;
|
|
110
128
|
}
|
|
@@ -152,7 +170,13 @@ const refreshAccessKey = async (req, res, _next) => {
|
|
|
152
170
|
if (!clientId) {
|
|
153
171
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "CLIENT_ID_NOT_FOUND");
|
|
154
172
|
}
|
|
155
|
-
if (!(0, import_permissions.hasPermission)(
|
|
173
|
+
if (!(0, import_permissions.hasPermission)(
|
|
174
|
+
roles,
|
|
175
|
+
"project:write"
|
|
176
|
+
)({
|
|
177
|
+
...res.locals,
|
|
178
|
+
targetProjectIds: [project.id]
|
|
179
|
+
})) {
|
|
156
180
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
157
181
|
return;
|
|
158
182
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/projectAccessKey.controller.ts"],"sourcesContent":["import type { AccessKeyData, OAuth2Access } from '@/types/project.types';\nimport { sendEmail } from '@services/email.service';\nimport * as projectAccessKeyService from '@services/projectAccessKey.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport { hasPermission } from '@utils/permissions';\nimport { type ResponseData, formatResponse } from '@utils/responseData';\nimport type { NextFunction, Request
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/projectAccessKey.controller.ts"],"sourcesContent":["import type { AccessKeyData, OAuth2Access } from '@/types/project.types';\nimport type { ResponseWithSession } from '@middlewares/sessionAuth.middleware';\nimport { sendEmail } from '@services/email.service';\nimport * as projectAccessKeyService from '@services/projectAccessKey.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport { hasPermission, intersectPermissions } from '@utils/permissions';\nimport { type ResponseData, formatResponse } from '@utils/responseData';\nimport type { NextFunction, Request } from 'express';\nimport { t } from 'express-intlayer';\n\nexport type AddNewAccessKeyBody = AccessKeyData;\nexport type AddNewAccessKeyResponse = ResponseData<OAuth2Access>;\n\n/**\n * Adds a new access key to a project.\n */\nexport const addNewAccessKey = async (\n req: Request<AddNewAccessKeyBody>,\n res: ResponseWithSession<AddNewAccessKeyResponse>,\n _next: NextFunction\n): Promise<void> => {\n const { user, project, roles, permissions } = res.locals;\n const { grants, name, expiresAt } = req.body;\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 (\n !hasPermission(\n roles,\n 'project:write'\n )({\n ...res.locals,\n targetProjectIds: [project.id],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const filteredPermisions = intersectPermissions(permissions, grants);\n\n try {\n const newAccessKey = await projectAccessKeyService.addNewAccessKey(\n {\n name,\n expiresAt,\n grants: filteredPermisions,\n },\n project.id,\n user\n );\n\n const responseData = formatResponse<OAuth2Access>({\n message: t({\n en: 'Access key created successfully',\n es: 'Clave de acceso creada con éxito',\n fr: \"Clé d'accès créée avec succès\",\n }),\n description: t({\n en: 'The access key has been created successfully',\n es: 'La clave de acceso ha sido creada con éxito',\n fr: \"La clé d'accès a été créée avec succès\",\n }),\n data: newAccessKey,\n });\n\n res.json(responseData);\n\n sendEmail({\n type: 'oAuthTokenCreated',\n to: user.email,\n username: user.name,\n applicationName: newAccessKey.name ?? newAccessKey.clientId,\n scopes: newAccessKey.grants,\n tokenDetailsUrl: `${process.env.CLIENT_URL}/oauth2/token`,\n securityLogUrl: `${process.env.CLIENT_URL}/security-log`,\n supportUrl: `${process.env.CLIENT_URL}/support`,\n });\n\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type DeleteAccessKeyBody = { clientId: string };\nexport type DeleteAccessKeyResponse = ResponseData<null>;\n\n/**\n * Deletes an access key from a project.\n */\nexport const deleteAccessKey = async (\n req: Request,\n res: ResponseWithSession<AddNewAccessKeyResponse>,\n _next: NextFunction\n): Promise<void> => {\n const { user, project, roles } = res.locals;\n const { clientId } = req.body;\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 (!clientId) {\n ErrorHandler.handleGenericErrorResponse(res, 'CLIENT_ID_NOT_FOUND');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'project:write'\n )({\n ...res.locals,\n targetProjectIds: [project.id],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const deletedAccessKey = await projectAccessKeyService.deleteAccessKey(\n clientId,\n project,\n user.id\n );\n\n if (!deletedAccessKey) {\n ErrorHandler.handleGenericErrorResponse(res, 'ACCESS_KEY_NOT_FOUND', {\n clientId,\n });\n return;\n }\n\n const responseData = formatResponse<null>({\n message: t({\n en: 'Access key deleted successfully',\n es: 'Clave de acceso eliminada con éxito',\n fr: \"Clé d'accès supprimée avec succès\",\n }),\n description: t({\n en: 'The access key has been deleted successfully',\n es: 'La clave de acceso ha sido eliminada con éxito',\n fr: \"La clé d'accès a été supprimée avec succès\",\n }),\n data: null,\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 RefreshAccessKeyBody = { clientId: string };\nexport type RefreshAccessKeyResponse = ResponseData<OAuth2Access>;\n\n/**\n * Refreshes an access key from a project.\n */\nexport const refreshAccessKey = async (\n req: Request<RefreshAccessKeyBody>,\n res: ResponseWithSession<RefreshAccessKeyResponse>,\n _next: NextFunction\n): Promise<void> => {\n const { user, project, roles } = res.locals;\n const { clientId } = req.body;\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n }\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n }\n\n if (!clientId) {\n ErrorHandler.handleGenericErrorResponse(res, 'CLIENT_ID_NOT_FOUND');\n }\n\n if (\n !hasPermission(\n roles,\n 'project:write'\n )({\n ...res.locals,\n targetProjectIds: [project!.id],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const newAccessKey = await projectAccessKeyService.refreshAccessKey(\n clientId,\n project!.id,\n user!.id\n );\n\n const responseData = formatResponse<OAuth2Access>({\n message: t({\n en: 'Access key refreshed successfully',\n es: 'Clave de acceso actualizada con éxito',\n fr: \"Clé d'accès actualisée avec succès\",\n }),\n description: t({\n en: 'The access key has been refreshed successfully',\n es: 'La clave de acceso ha sido actualizada con éxito',\n fr: \"La clé d'accès a été actualisée avec succès\",\n }),\n data: newAccessKey,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0B;AAC1B,8BAAyC;AACzC,oBAA4C;AAC5C,yBAAoD;AACpD,0BAAkD;AAElD,8BAAkB;AAQX,MAAM,kBAAkB,OAC7B,KACA,KACA,UACkB;AAClB,QAAM,EAAE,MAAM,SAAS,OAAO,YAAY,IAAI,IAAI;AAClD,QAAM,EAAE,QAAQ,MAAM,UAAU,IAAI,IAAI;AAExC,MAAI,CAAC,SAAS;AACZ,+BAAa,2BAA2B,KAAK,qBAAqB;AAClE;AAAA,EACF;AAEA,MAAI,CAAC,MAAM;AACT,+BAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AAEA,MACE,KAAC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EAAE;AAAA,IACA,GAAG,IAAI;AAAA,IACP,kBAAkB,CAAC,QAAQ,EAAE;AAAA,EAC/B,CAAC,GACD;AACA,+BAAa,2BAA2B,KAAK,mBAAmB;AAChE;AAAA,EACF;AAEA,QAAM,yBAAqB,yCAAqB,aAAa,MAAM;AAEnE,MAAI;AACF,UAAM,eAAe,MAAM,wBAAwB;AAAA,MACjD;AAAA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ACT,KAAM;AAAA,IACR;AAEA,UAAM,mBAAe,oCAA6B;AAAA,MAChD,aAAS,2BAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,iBAAa,2BAAE;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,+BAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/search.controller.ts"],"sourcesContent":["import * as askDocQuestionUtil from '@utils/AI/askDocQuestion/askDocQuestion';\
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/search.controller.ts"],"sourcesContent":["import * as askDocQuestionUtil from '@utils/AI/askDocQuestion/askDocQuestion';\nimport { formatResponse, type ResponseData } from '@utils/responseData';\nimport type { Request, Response } from 'express';\n\nexport type SearchDocUtilParams = {\n input: string;\n};\nexport type SearchDocUtilResult = ResponseData<string[]>;\n\nexport const searchDocUtil = async (\n req: Request<unknown, unknown, unknown, SearchDocUtilParams>,\n res: Response<SearchDocUtilResult>\n) => {\n const { input } = req.query;\n\n const response = await askDocQuestionUtil.searchChunkReference(\n input,\n 30,\n 0.2\n );\n const docFileList = response.map((doc) => doc.fileKey);\n\n const uniqueDocFileList = Array.from(new Set(docFileList));\n\n const responseData = formatResponse<string[]>({\n data: uniqueDocFileList,\n });\n\n res.json(responseData);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAoC;AACpC,0BAAkD;AAQ3C,MAAM,gBAAgB,OAC3B,KACA,QACG;AACH,QAAM,EAAE,MAAM,IAAI,IAAI;AAEtB,QAAM,WAAW,MAAM,mBAAmB;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,cAAc,SAAS,IAAI,CAAC,QAAQ,IAAI,OAAO;AAErD,QAAM,oBAAoB,MAAM,KAAK,IAAI,IAAI,WAAW,CAAC;AAEzD,QAAM,mBAAe,oCAAyB;AAAA,IAC5C,MAAM;AAAA,EACR,CAAC;AAED,MAAI,KAAK,YAAY;AACvB;","names":[]}
|
|
@@ -90,8 +90,7 @@ const getSubscription = async (req, res) => {
|
|
|
90
90
|
// Associate the subscription with the customer
|
|
91
91
|
items: [{ price: priceId }],
|
|
92
92
|
// Set the price ID for the subscription
|
|
93
|
-
expand: ["latest_invoice.
|
|
94
|
-
// Expand to get payment intent details
|
|
93
|
+
expand: ["latest_invoice.confirmation_secret"],
|
|
95
94
|
payment_settings: {
|
|
96
95
|
payment_method_types: ["card"]
|
|
97
96
|
// Specify payment method types
|
|
@@ -112,8 +111,21 @@ const getSubscription = async (req, res) => {
|
|
|
112
111
|
);
|
|
113
112
|
return;
|
|
114
113
|
}
|
|
114
|
+
const clientSecret = subscription.latest_invoice?.confirmation_secret?.client_secret;
|
|
115
|
+
if (!clientSecret) {
|
|
116
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(
|
|
117
|
+
res,
|
|
118
|
+
"SUBSCRIPTION_CREATION_FAILED",
|
|
119
|
+
{
|
|
120
|
+
user,
|
|
121
|
+
organization,
|
|
122
|
+
priceId
|
|
123
|
+
}
|
|
124
|
+
);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
115
127
|
const responseData = (0, import_responseData.formatResponse)({
|
|
116
|
-
data: subscription
|
|
128
|
+
data: { subscription, clientSecret }
|
|
117
129
|
});
|
|
118
130
|
res.json(responseData);
|
|
119
131
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/stripe.controller.ts"],"sourcesContent":["import type { Organization } from '@/types/organization.types';\nimport * as emailService from '@services/email.service';\nimport * as subscriptionService from '@services/subscription.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport { type ResponseData, formatResponse } from '@utils/responseData';\nimport type { Request, Response } from 'express';\nimport { t } from 'express-intlayer';\nimport type { Locales } from 'intlayer';\nimport { Stripe } from 'stripe';\n\nexport type GetPricingBody = {\n priceIds: string[];\n promoCode?: string;\n};\n\nexport type GetPricingResult = ResponseData<subscriptionService.PricingResult>;\n\n/**\n * Simulate pricing for a given set of prices and a promotion code.\n *\n * @param req - The request object containing the price IDs and promotion code.\n * @param res - The response object to send the simulated pricing result.\n */\nexport const getPricing = async (\n req: Request<undefined, undefined, GetPricingBody>,\n res: Response<GetPricingResult>\n) => {\n const { priceIds, promoCode } = req.body;\n\n const pricingResult = await subscriptionService.getPricing(\n priceIds,\n promoCode\n );\n\n const formattedPricingResult =\n formatResponse<subscriptionService.PricingResult>({\n data: pricingResult,\n });\n\n res.status(200).json(formattedPricingResult);\n};\n\nexport type GetCheckoutSessionBody = {\n priceId: string;\n promoCode?: string;\n};\n\nexport type GetCheckoutSessionResult = ResponseData<\n Stripe.Response<Stripe.Subscription>\n>;\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: Response<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, promoCode } = 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 const { period, type } = retrievePlanInformation(priceId);\n\n if (\n organization.plan?.subscriptionId &&\n organization.plan?.type === type &&\n organization.plan?.period === period &&\n organization.plan?.status === 'active'\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 const promoCodeId = promoCode\n ? await subscriptionService.getCouponId(promoCode)\n : null;\n\n const discounts: Stripe.SubscriptionCreateParams.Discount[] = promoCodeId\n ? [{ coupon: promoCodeId }]\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 discounts: discounts,\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<Stripe.Response<Stripe.Subscription>>({\n data: subscription,\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: Response<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 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\n await emailService.sendEmail({\n type: 'subscriptionPaymentCancellation',\n to: user.email,\n email: user.email,\n cancellationDate: new Date().toLocaleDateString(),\n reactivateLink: `${process.env.CLIENT_URL}/pricing`,\n username: user.name,\n organizationName: organization.name,\n planName: plan.type,\n });\n } catch (error) {\n // Handle any errors that occur during the cancellation process\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n }\n};\n"],"m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UAAM,OAAO,cAAc,OAAO,aAAa,KAAK,cAAc;AAGlE,UAAM,OAAO,MAAM,oBAAoB;AAAA,MACrC,aAAa,KAAK;AAAA,MAClB,OAAO,aAAa,EAAE;AAAA,IACxB;AAGA,QAAI,CAAC,MAAM;AACT,iCAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAGA,UAAM,oBAAgB,oCAAuC;AAAA,MAC3D,aAAS,2BAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,iBAAa,2BAAE;AAAA,QACb,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,MAAM;AAAA,IACR,CAAC;AAGD,QAAI,KAAK,aAAa;AAEtB,UAAM,aAAa,UAAU;AAAA,MAC3B,MAAM;AAAA,MACN,IAAI,KAAK;AAAA,MACT,OAAO,KAAK;AAAA,MACZ,mBAAkB,oBAAI,KAAK,GAAE,mBAAmB;AAAA,MAChD,gBAAgB,GAAG,QAAQ,IAAI,UAAU;AAAA,MACzC,UAAU,KAAK;AAAA,MACf,kBAAkB,aAAa;AAAA,MAC/B,UAAU,KAAK;AAAA,IACjB,CAAC;AAAA,EACH,SAAS,OAAO;AAEd,+BAAa,uBAAuB,KAAK,KAAiB;AAAA,EAC5D;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/stripe.controller.ts"],"sourcesContent":["import type { Organization } from '@/types/organization.types';\nimport type { ResponseWithSession } from '@middlewares/sessionAuth.middleware';\nimport * as emailService from '@services/email.service';\nimport * as subscriptionService from '@services/subscription.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport { type ResponseData, formatResponse } from '@utils/responseData';\nimport type { Request } from 'express';\nimport { t } from 'express-intlayer';\nimport type { Locales } from 'intlayer';\nimport { Stripe } from 'stripe';\n\nexport type GetPricingBody = {\n priceIds: string[];\n promoCode?: string;\n};\n\nexport type GetPricingResult = ResponseData<subscriptionService.PricingResult>;\n\n/**\n * Simulate pricing for a given set of prices and a promotion code.\n *\n * @param req - The request object containing the price IDs and promotion code.\n * @param res - The response object to send the simulated pricing result.\n */\nexport const getPricing = async (\n req: Request<undefined, undefined, GetPricingBody>,\n res: ResponseWithSession<GetPricingResult>\n) => {\n const { priceIds, promoCode } = req.body;\n\n const pricingResult = await subscriptionService.getPricing(\n priceIds,\n promoCode\n );\n\n const formattedPricingResult =\n formatResponse<subscriptionService.PricingResult>({\n data: pricingResult,\n });\n\n res.status(200).json(formattedPricingResult);\n};\n\nexport type GetCheckoutSessionBody = {\n priceId: string;\n promoCode?: string;\n};\n\nexport type GetCheckoutSessionResult = ResponseData<{\n subscription: Stripe.Response<Stripe.Subscription>;\n clientSecret: string;\n}>;\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: ResponseWithSession<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, promoCode } = 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 const { period, type } = retrievePlanInformation(priceId);\n\n if (\n organization.plan?.subscriptionId &&\n organization.plan?.type === type &&\n organization.plan?.period === period &&\n organization.plan?.status === 'active'\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 const promoCodeId = promoCode\n ? await subscriptionService.getCouponId(promoCode)\n : null;\n\n const discounts: Stripe.SubscriptionCreateParams.Discount[] = promoCodeId\n ? [{ coupon: promoCodeId }]\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.confirmation_secret'],\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 discounts,\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 const clientSecret = (\n subscription.latest_invoice as Stripe.Invoice & {\n confirmation_secret?: { client_secret: string };\n }\n )?.confirmation_secret?.client_secret;\n\n // Handle subscription creation failure\n if (!clientSecret) {\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<GetCheckoutSessionResult['data']>({\n data: { subscription, clientSecret },\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: ResponseWithSession<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 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\n await emailService.sendEmail({\n type: 'subscriptionPaymentCancellation',\n to: user.email,\n email: user.email,\n cancellationDate: new Date().toLocaleDateString(),\n reactivateLink: `${process.env.CLIENT_URL}/pricing`,\n username: user.name,\n organizationName: organization.name,\n planName: plan.type,\n });\n } catch (error) {\n // Handle any errors that occur during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QAAI,CAAC,cAAc;AACjB,iCAAa,2BAA2B,KAAK,wBAAwB;AACrE;AAAA,IACF;AAGA,QAAI,CAAC,MAAM;AACT,iCAAa,2BAA2B,KAAK,gBAAgB;AAC7D;AAAA,IACF;AAGA,QAAI,CAAC,aAAa,MAAM,gBAAgB;AACtC,iCAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAGA,UAAM,OAAO,cAAc,OAAO,aAAa,KAAK,cAAc;AAGlE,UAAM,OAAO,MAAM,oBAAoB;AAAA,MACrC,aAAa,KAAK;AAAA,MAClB,OAAO,aAAa,EAAE;AAAA,IACxB;AAGA,QAAI,CAAC,MAAM;AACT,iCAAa;AAAA,QACX;AAAA,QACA;AAAA,MACF;AACA;AAAA,IACF;AAGA,UAAM,oBAAgB,oCAAuC;AAAA,MAC3D,aAAS,2BAAE;AAAA,QACT,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,iBAAa,2BAAE;AAAA,QACb,IAAI;AAAA,QACJ,IAAI;AAAA,QACJ,IAAI;AAAA,MACN,CAAC;AAAA,MACD,MAAM;AAAA,IACR,CAAC;AAGD,QAAI,KAAK,aAAa;AAEtB,UAAM,aAAa,UAAU;AAAA,MAC3B,MAAM;AAAA,MACN,IAAI,KAAK;AAAA,MACT,OAAO,KAAK;AAAA,MACZ,mBAAkB,oBAAI,KAAK,GAAE,mBAAmB;AAAA,MAChD,gBAAgB,GAAG,QAAQ,IAAI,UAAU;AAAA,MACzC,UAAU,KAAK;AAAA,MACf,kBAAkB,aAAa;AAAA,MAC/B,UAAU,KAAK;AAAA,IACjB,CAAC;AAAA,EACH,SAAS,OAAO;AAEd,+BAAa,uBAAuB,KAAK,KAAiB;AAAA,EAC5D;AACF;","names":[]}
|
|
@@ -53,16 +53,22 @@ const getTags = async (req, res, _next) => {
|
|
|
53
53
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_DEFINED");
|
|
54
54
|
return;
|
|
55
55
|
}
|
|
56
|
-
if (!(0, import_permissions.hasPermission)(roles, "tag:read")()) {
|
|
57
|
-
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
56
|
const restrictedFilter = {
|
|
61
57
|
...filters,
|
|
62
58
|
organizationId: String(organization.id)
|
|
63
59
|
};
|
|
64
60
|
try {
|
|
65
61
|
const tags = await tagService.findTags(restrictedFilter, skip, pageSize);
|
|
62
|
+
if (!(0, import_permissions.hasPermission)(
|
|
63
|
+
roles,
|
|
64
|
+
"tag:read"
|
|
65
|
+
)({
|
|
66
|
+
...res.locals,
|
|
67
|
+
targetTags: tags
|
|
68
|
+
})) {
|
|
69
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
66
72
|
const totalItems = await tagService.countTags(filters);
|
|
67
73
|
const formattedTags = (0, import_tag.mapTagsToAPI)(tags);
|
|
68
74
|
const responseData = (0, import_responseData.formatPaginatedResponse)({
|
|
@@ -80,7 +86,7 @@ const getTags = async (req, res, _next) => {
|
|
|
80
86
|
}
|
|
81
87
|
};
|
|
82
88
|
const addTag = async (req, res, _next) => {
|
|
83
|
-
const { organization, user, roles } = res.locals;
|
|
89
|
+
const { organization, project, user, roles } = res.locals;
|
|
84
90
|
const tagData = req.body;
|
|
85
91
|
if (!user) {
|
|
86
92
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
|
|
@@ -90,18 +96,29 @@ const addTag = async (req, res, _next) => {
|
|
|
90
96
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_DEFINED");
|
|
91
97
|
return;
|
|
92
98
|
}
|
|
99
|
+
if (!project) {
|
|
100
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PROJECT_NOT_DEFINED");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
93
103
|
if (!tagData) {
|
|
94
104
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PROJECT_DATA_NOT_FOUND");
|
|
95
105
|
}
|
|
96
|
-
if (!(0, import_permissions.hasPermission)(roles, "tag:admin")(res.locals)) {
|
|
97
|
-
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
106
|
const tag = {
|
|
101
107
|
creatorId: user.id,
|
|
102
108
|
organizationId: organization.id,
|
|
109
|
+
projectId: project.id,
|
|
103
110
|
...tagData
|
|
104
111
|
};
|
|
112
|
+
if (!(0, import_permissions.hasPermission)(
|
|
113
|
+
roles,
|
|
114
|
+
"tag:admin"
|
|
115
|
+
)({
|
|
116
|
+
...res.locals,
|
|
117
|
+
targetTags: [tag]
|
|
118
|
+
})) {
|
|
119
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
105
122
|
try {
|
|
106
123
|
const newTag = await tagService.createTag(tag);
|
|
107
124
|
const formattedTag = (0, import_tag.mapTagToAPI)(newTag);
|
|
@@ -136,10 +153,6 @@ const updateTag = async (req, res, _next) => {
|
|
|
136
153
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "ORGANIZATION_NOT_DEFINED");
|
|
137
154
|
return;
|
|
138
155
|
}
|
|
139
|
-
if (!(0, import_permissions.hasPermission)(roles, "tag:write")()) {
|
|
140
|
-
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
156
|
try {
|
|
144
157
|
const tag = {
|
|
145
158
|
_id: tagId,
|
|
@@ -149,6 +162,16 @@ const updateTag = async (req, res, _next) => {
|
|
|
149
162
|
instructions: req.body.instructions
|
|
150
163
|
};
|
|
151
164
|
const tagToDelete = await tagService.getTagById(tagId);
|
|
165
|
+
if (!(0, import_permissions.hasPermission)(
|
|
166
|
+
roles,
|
|
167
|
+
"tag:write"
|
|
168
|
+
)({
|
|
169
|
+
...res.locals,
|
|
170
|
+
targetTags: [tagToDelete]
|
|
171
|
+
})) {
|
|
172
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
152
175
|
if (String(tagToDelete.organizationId) !== String(organization.id)) {
|
|
153
176
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "TAG_NOT_IN_ORGANIZATION");
|
|
154
177
|
return;
|
|
@@ -190,12 +213,18 @@ const deleteTag = async (req, res, _next) => {
|
|
|
190
213
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "TAG_ID_NOT_FOUND");
|
|
191
214
|
return;
|
|
192
215
|
}
|
|
193
|
-
if (!(0, import_permissions.hasPermission)(roles, "tag:admin")(res.locals)) {
|
|
194
|
-
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
195
|
-
return;
|
|
196
|
-
}
|
|
197
216
|
try {
|
|
198
217
|
const tagToDelete = await tagService.getTagById(tagId);
|
|
218
|
+
if (!(0, import_permissions.hasPermission)(
|
|
219
|
+
roles,
|
|
220
|
+
"tag:admin"
|
|
221
|
+
)({
|
|
222
|
+
...res.locals,
|
|
223
|
+
targetTags: [tagToDelete]
|
|
224
|
+
})) {
|
|
225
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
199
228
|
if (String(tagToDelete.organizationId) !== String(organization.id)) {
|
|
200
229
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "TAG_NOT_IN_ORGANIZATION");
|
|
201
230
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/tag.controller.ts"],"sourcesContent":["import type {\n Tag,\n TagAPI,\n TagCreationData,\n TagData,\n TagSchema,\n} from '@/types/tag.types';\nimport { logger } from '@logger';\nimport * as tagService from '@services/tag.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport {\n getTagFiltersAndPagination,\n type TagFilters,\n type TagFiltersParams,\n} from '@utils/filtersAndPagination/getTagFiltersAndPagination';\nimport { mapTagsToAPI, mapTagToAPI } from '@utils/mapper/tag';\nimport { hasPermission } from '@utils/permissions';\nimport {\n formatPaginatedResponse,\n formatResponse,\n type PaginatedResponse,\n type ResponseData,\n} from '@utils/responseData';\nimport type { NextFunction, Request, Response } from 'express';\nimport { t } from 'express-intlayer';\n\nexport type GetTagsParams = FiltersAndPagination<TagFiltersParams>;\nexport type GetTagsResult = PaginatedResponse<TagAPI>;\n\n/**\n * Retrieves a list of tags based on filters and pagination.\n */\nexport const getTags = async (\n req: Request<GetTagsParams>,\n res: Response<GetTagsResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, organization, roles } = res.locals;\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getTagFiltersAndPagination(req);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!hasPermission(roles, 'tag:read')()) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const restrictedFilter: TagFilters = {\n ...filters,\n organizationId: String(organization.id),\n };\n\n try {\n const tags = await tagService.findTags(restrictedFilter, skip, pageSize);\n const totalItems = await tagService.countTags(filters);\n\n const formattedTags = mapTagsToAPI(tags);\n\n const responseData = formatPaginatedResponse<TagAPI>({\n data: formattedTags,\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 AddTagBody = TagCreationData;\nexport type AddTagResult = ResponseData<TagAPI>;\n\n/**\n * Adds a new tag to the database.\n */\nexport const addTag = async (\n req: Request<any, any, AddTagBody>,\n res: Response<AddTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { organization, user, roles } = res.locals;\n const tagData = req.body;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!tagData) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_DATA_NOT_FOUND');\n }\n\n if (!hasPermission(roles, 'tag:admin')(res.locals)) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const tag: TagData = {\n creatorId: user.id,\n organizationId: organization.id,\n ...tagData,\n };\n\n try {\n const newTag = await tagService.createTag(tag);\n\n const formattedTag = mapTagToAPI(newTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag created successfully',\n fr: 'Tag créé avec succès',\n es: 'Tag creado con éxito',\n }),\n description: t({\n en: 'Your tag has been created successfully',\n fr: 'Votre tag a été créé avec succès',\n es: 'Su tag ha sido creado con éxito',\n }),\n data: formattedTag,\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 UpdateTagParams = { tagId: string | Tag['id'] };\nexport type UpdateTagBody = Partial<TagData>;\nexport type UpdateTagResult = ResponseData<TagAPI>;\n\n/**\n * Updates an existing tag in the database.\n */\nexport const updateTag = async (\n req: Request<UpdateTagParams, any, UpdateTagBody>,\n res: Response<UpdateTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { tagId } = req.params;\n const { organization, user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!hasPermission(roles, 'tag:write')()) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const tag = {\n _id: tagId,\n name: req.body.name,\n key: req.body.key,\n description: req.body.description,\n instructions: req.body.instructions,\n } as Partial<TagSchema> & { _id: Tag['id'] };\n\n const tagToDelete = await tagService.getTagById(tagId);\n\n if (String(tagToDelete.organizationId) !== String(organization.id)) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_IN_ORGANIZATION');\n return;\n }\n\n const updatedTag = await tagService.updateTagById(tag._id, tag);\n\n const formattedTag = mapTagToAPI(updatedTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag updated successfully',\n fr: 'Tag mis à jour avec succès',\n es: 'Tag actualizado con éxito',\n }),\n description: t({\n en: 'Your tag has been updated successfully',\n fr: 'Votre tag a été mis à jour avec succès',\n es: 'Su tag ha sido actualizado con éxito',\n }),\n data: formattedTag,\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 DeleteTagParams = { tagId: string | Tag['id'] };\nexport type DeleteTagResult = ResponseData<TagAPI>;\n\n/**\n * Deletes a tag from the database by its ID.\n * @param req - Express request object.\n * @param res - Express response object.\n * @returns Response confirming the deletion.\n */\nexport const deleteTag = async (\n req: Request<DeleteTagParams>,\n res: Response<DeleteTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, organization, roles } = res.locals;\n const { tagId } = req.params;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!tagId) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_ID_NOT_FOUND');\n return;\n }\n\n if (!hasPermission(roles, 'tag:admin')(res.locals)) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const tagToDelete = await tagService.getTagById(tagId);\n\n if (String(tagToDelete.organizationId) !== String(organization.id)) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_IN_ORGANIZATION');\n return;\n }\n\n const deletedTag = await tagService.deleteTagById(tagId);\n\n if (!deletedTag) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_FOUND', {\n tagId,\n });\n\n return;\n }\n\n logger.info(`Tag deleted: ${String(deletedTag.id)}`);\n\n const formattedTag = mapTagToAPI(deletedTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag deleted successfully',\n fr: 'Tag supprimé avec succès',\n es: 'Tag eliminado con éxito',\n }),\n description: t({\n en: 'Your tag has been deleted successfully',\n fr: 'Votre tag a été supprimé avec succès',\n es: 'Su tag ha sido eliminado con éxito',\n }),\n data: formattedTag,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,oBAAuB;AACvB,iBAA4B;AAC5B,oBAA4C;AAE5C,wCAIO;AACP,iBAA0C;AAC1C,yBAA8B;AAC9B,0BAKO;AAEP,8BAAkB;AAQX,MAAM,UAAU,OACrB,KACA,KACA,UACkB;AAClB,QAAM,EAAE,MAAM,cAAc,MAAM,IAAI,IAAI;AAC1C,QAAM,EAAE,SAAS,UAAU,MAAM,MAAM,iBAAiB,QACtD,8DAA2B,GAAG;AAEhC,MAAI,CAAC,MAAM;AACT,+BAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AAEA,MAAI,CAAC,cAAc;AACjB,+BAAa,2BAA2B,KAAK,0BAA0B;AACvE;AAAA,EACF;AAEA,MAAI,KAAC,kCAAc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AAA,MACN,CAAC;AAAA,MACD,iBAAa,2BAAE;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,+BAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/tag.controller.ts"],"sourcesContent":["import type {\n Tag,\n TagAPI,\n TagCreationData,\n TagData,\n TagSchema,\n} from '@/types/tag.types';\nimport { logger } from '@logger';\nimport type { ResponseWithSession } from '@middlewares/sessionAuth.middleware';\nimport * as tagService from '@services/tag.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport {\n getTagFiltersAndPagination,\n type TagFilters,\n type TagFiltersParams,\n} from '@utils/filtersAndPagination/getTagFiltersAndPagination';\nimport { mapTagsToAPI, mapTagToAPI } from '@utils/mapper/tag';\nimport { hasPermission } from '@utils/permissions';\nimport {\n formatPaginatedResponse,\n formatResponse,\n type PaginatedResponse,\n type ResponseData,\n} from '@utils/responseData';\nimport type { NextFunction, Request } from 'express';\nimport { t } from 'express-intlayer';\n\nexport type GetTagsParams = FiltersAndPagination<TagFiltersParams>;\nexport type GetTagsResult = PaginatedResponse<TagAPI>;\n\n/**\n * Retrieves a list of tags based on filters and pagination.\n */\nexport const getTags = async (\n req: Request<GetTagsParams>,\n res: ResponseWithSession<GetTagsResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, organization, roles } = res.locals;\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getTagFiltersAndPagination(req);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n const restrictedFilter: TagFilters = {\n ...filters,\n organizationId: String(organization.id),\n };\n\n try {\n const tags = await tagService.findTags(restrictedFilter, skip, pageSize);\n\n if (\n !hasPermission(\n roles,\n 'tag:read'\n )({\n ...res.locals,\n targetTags: tags,\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const totalItems = await tagService.countTags(filters);\n\n const formattedTags = mapTagsToAPI(tags);\n\n const responseData = formatPaginatedResponse<TagAPI>({\n data: formattedTags,\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 AddTagBody = TagCreationData;\nexport type AddTagResult = ResponseData<TagAPI>;\n\n/**\n * Adds a new tag to the database.\n */\nexport const addTag = async (\n req: Request<any, any, AddTagBody>,\n res: ResponseWithSession<AddTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { organization, project, user, roles } = res.locals;\n const tagData = req.body;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!project) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_NOT_DEFINED');\n return;\n }\n\n if (!tagData) {\n ErrorHandler.handleGenericErrorResponse(res, 'PROJECT_DATA_NOT_FOUND');\n }\n\n const tag: TagData = {\n creatorId: user.id,\n organizationId: organization.id,\n projectId: project.id,\n ...tagData,\n };\n\n if (\n !hasPermission(\n roles,\n 'tag:admin'\n )({\n ...res.locals,\n targetTags: [tag as Tag],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const newTag = await tagService.createTag(tag);\n\n const formattedTag = mapTagToAPI(newTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag created successfully',\n fr: 'Tag créé avec succès',\n es: 'Tag creado con éxito',\n }),\n description: t({\n en: 'Your tag has been created successfully',\n fr: 'Votre tag a été créé avec succès',\n es: 'Su tag ha sido creado con éxito',\n }),\n data: formattedTag,\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 UpdateTagParams = { tagId: string | Tag['id'] };\nexport type UpdateTagBody = Partial<TagData>;\nexport type UpdateTagResult = ResponseData<TagAPI>;\n\n/**\n * Updates an existing tag in the database.\n */\nexport const updateTag = async (\n req: Request<UpdateTagParams, any, UpdateTagBody>,\n res: ResponseWithSession<UpdateTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { tagId } = req.params;\n const { organization, user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n try {\n const tag = {\n _id: tagId,\n name: req.body.name,\n key: req.body.key,\n description: req.body.description,\n instructions: req.body.instructions,\n } as Partial<TagSchema> & { _id: Tag['id'] };\n\n const tagToDelete = await tagService.getTagById(tagId);\n\n if (\n !hasPermission(\n roles,\n 'tag:write'\n )({\n ...res.locals,\n targetTags: [tagToDelete],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n if (String(tagToDelete.organizationId) !== String(organization.id)) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_IN_ORGANIZATION');\n return;\n }\n\n const updatedTag = await tagService.updateTagById(tag._id, tag);\n\n const formattedTag = mapTagToAPI(updatedTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag updated successfully',\n fr: 'Tag mis à jour avec succès',\n es: 'Tag actualizado con éxito',\n }),\n description: t({\n en: 'Your tag has been updated successfully',\n fr: 'Votre tag a été mis à jour avec succès',\n es: 'Su tag ha sido actualizado con éxito',\n }),\n data: formattedTag,\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 DeleteTagParams = { tagId: string | Tag['id'] };\nexport type DeleteTagResult = ResponseData<TagAPI>;\n\n/**\n * Deletes a tag from the database by its ID.\n * @param req - Express request object.\n * @param res - Express response object.\n * @returns Response confirming the deletion.\n */\nexport const deleteTag = async (\n req: Request<DeleteTagParams>,\n res: ResponseWithSession<DeleteTagResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, organization, roles } = res.locals;\n const { tagId } = req.params;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (!organization) {\n ErrorHandler.handleGenericErrorResponse(res, 'ORGANIZATION_NOT_DEFINED');\n return;\n }\n\n if (!tagId) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_ID_NOT_FOUND');\n return;\n }\n\n try {\n const tagToDelete = await tagService.getTagById(tagId);\n\n if (\n !hasPermission(\n roles,\n 'tag:admin'\n )({\n ...res.locals,\n targetTags: [tagToDelete],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n if (String(tagToDelete.organizationId) !== String(organization.id)) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_IN_ORGANIZATION');\n return;\n }\n\n const deletedTag = await tagService.deleteTagById(tagId);\n\n if (!deletedTag) {\n ErrorHandler.handleGenericErrorResponse(res, 'TAG_NOT_FOUND', {\n tagId,\n });\n\n return;\n }\n\n logger.info(`Tag deleted: ${String(deletedTag.id)}`);\n\n const formattedTag = mapTagToAPI(deletedTag);\n\n const responseData = formatResponse<TagAPI>({\n message: t({\n en: 'Tag deleted successfully',\n fr: 'Tag supprimé avec succès',\n es: 'Tag eliminado con éxito',\n }),\n description: t({\n en: 'Your tag has been deleted successfully',\n fr: 'Votre tag a été supprimé avec succès',\n es: 'Su tag ha sido eliminado con éxito',\n }),\n data: formattedTag,\n });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,oBAAuB;AAEvB,iBAA4B;AAC5B,oBAA4C;AAE5C,wCAIO;AACP,iBAA0C;AAC1C,yBAA8B;AAC9B,0BAKO;AAEP,8BAAkB;AAQX,MAAM,UAAU,OACrB,KACA,KACA,UACkB;AAClB,QAAM,EAAE,MAAM,cAAc,MAAM,IAAI,IAAI;AAC1C,QAAM,EAAE,SAAS,UAAU,MAAM,MAAM,iBAAiB,QACtD,8DAA2B,GAAG;AAEhC,MAAI,CAAC,MAAM;AACT,+BAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AAEA,MAAI,CAAC,cAAc;AACjB,+BAAa,2BAA2B,KAAK,0BAA0B;AACvE;AAAA,EACF;AAEA,QAAM,mBAA+B;AAAA,IACnC,GAAG;AAAA,IACH,gBAAgB,OAAO,aAAa,EAAE;AAAA,EACxC;AAEA,MAAI;AACF,UAAM,OAAO,MAAM,WAAW,SAAS,kBAAkB,MAAM,QAAQ;AAEvE,QACE,KAAC;AAAA,MACC;AAAA,MACA;AAAA,IACF,EAAE;AAAA,MACA,GAAG,IAAI;AAAA,MACP,YAAY;AAAA,IACd,CAAC,GACD;AACA,iCAAa,2BAA2B,KAAK,mBAAmB;AAChE;AAAA,IACF;AAEA,UAAM,aAAa,MAAM,WAAW,UAAU,OAAO;AAErD,UAAM,oBAAgB,yBAAa,IAAI;AAEvC,UAAM,mBAAe,6CAAgC;AAAA,MACnD,MAAM;AAAA,MACN;AAAA,MACA;AAAA,MACA,YAAY,iBAAiB,UAAU;AAAA,MACvC;AAAA,IACF,CAAC;AAED,QAA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AM;AAAA,IACR,CAAC;AAED,QAAI,KAAK,YAAY;AACrB;AAAA,EACF,SAAS,OAAO;AACd,+BAAa,uBAAuB,KAAK,KAAiB;AAC1D;AAAA,EACF;AACF;","names":[]}
|
|
@@ -96,7 +96,7 @@ const getUsers = async (req, res, _next) => {
|
|
|
96
96
|
"user:read"
|
|
97
97
|
)({
|
|
98
98
|
...res.locals,
|
|
99
|
-
|
|
99
|
+
targetUsers: users
|
|
100
100
|
})) {
|
|
101
101
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
102
102
|
return;
|
|
@@ -148,7 +148,7 @@ const getUserByEmail = async (req, res, _next) => {
|
|
|
148
148
|
"user:read"
|
|
149
149
|
)({
|
|
150
150
|
...res.locals,
|
|
151
|
-
|
|
151
|
+
targetUsers: [user]
|
|
152
152
|
})) {
|
|
153
153
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
154
154
|
return;
|
|
@@ -177,7 +177,7 @@ const updateUser = async (req, res, _next) => {
|
|
|
177
177
|
"user:write"
|
|
178
178
|
)({
|
|
179
179
|
...res.locals,
|
|
180
|
-
|
|
180
|
+
targetUsers: [userData]
|
|
181
181
|
})) {
|
|
182
182
|
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
183
183
|
return;
|
|
@@ -211,12 +211,23 @@ const updateUser = async (req, res, _next) => {
|
|
|
211
211
|
const deleteUser = async (req, res, _next) => {
|
|
212
212
|
const { userId } = req.params;
|
|
213
213
|
const { roles } = res.locals;
|
|
214
|
-
if (!(0, import_permissions.hasPermission)(roles, "user:admin")()) {
|
|
215
|
-
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
216
|
-
return;
|
|
217
|
-
}
|
|
218
214
|
try {
|
|
219
|
-
const user = await userService.
|
|
215
|
+
const user = await userService.getUserById(userId);
|
|
216
|
+
if (!user) {
|
|
217
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_FOUND");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (!(0, import_permissions.hasPermission)(
|
|
221
|
+
roles,
|
|
222
|
+
"user:admin"
|
|
223
|
+
)({
|
|
224
|
+
...res.locals,
|
|
225
|
+
targetUsers: [user]
|
|
226
|
+
})) {
|
|
227
|
+
import_errors.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
await userService.deleteUser(userId);
|
|
220
231
|
const formattedUser = (0, import_user.mapUserToAPI)(user);
|
|
221
232
|
const responseData = (0, import_responseData.formatResponse)({
|
|
222
233
|
message: (0, import_express_intlayer.t)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/user.controller.ts"],"sourcesContent":["import type { User, UserAPI } from '@/types/user.types';\nimport { logger } from '@logger';\nimport { sendEmail } from '@services/email.service';\nimport * as userService from '@services/user.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport { getOrganizationFiltersAndPagination } from '@utils/filtersAndPagination/getOrganizationFiltersAndPagination';\nimport type { UserFiltersParam } from '@utils/filtersAndPagination/getUserFiltersAndPagination';\nimport { mapUsersToAPI, mapUserToAPI } from '@utils/mapper/user';\nimport { hasPermission } from '@utils/permissions';\nimport {\n formatPaginatedResponse,\n formatResponse,\n type PaginatedResponse,\n type ResponseData,\n} from '@utils/responseData';\nimport type { NextFunction, Request, Response } from 'express';\nimport { t } from 'express-intlayer';\n\nexport type CreateUserBody = { email: string; password?: string };\nexport type CreateUserResult = ResponseData<UserAPI>;\n\n/**\n * Creates a new user.\n */\nexport const createUser = async (\n req: Request<any, any, User>,\n res: Response<CreateUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const user: User | undefined = req.body;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n try {\n const newUser = await userService.createUser(user);\n\n await sendEmail({\n type: 'welcome',\n to: newUser.email,\n username: newUser.name,\n loginLink: `${process.env.CLIENT_URL}/auth/login`,\n });\n\n const formattedUser = mapUserToAPI(newUser);\n\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User created',\n fr: 'Utilisateur créé',\n es: 'Usuario creado',\n }),\n description: t({\n en: 'User created successfully',\n fr: 'Utilisateur créé avec succès',\n es: 'Usuario creado con éxito',\n }),\n data: formattedUser,\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 GetUsersParams = FiltersAndPagination<UserFiltersParam>;\nexport type GetUsersResult = PaginatedResponse<UserAPI>;\n\n/**\n * Retrieves a list of users based on filters and pagination.\n */\nexport const getUsers = async (\n req: Request<GetUsersParams>,\n res: Response<GetUsersResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getOrganizationFiltersAndPagination(req);\n\n try {\n const users = await userService.findUsers(filters, skip, pageSize);\n\n if (\n !hasPermission(\n roles,\n 'user:read'\n )({\n ...res.locals,\n targetUserIds: users.map((user) => user.id),\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const totalItems = await userService.countUsers(filters);\n\n const formattedUsers = mapUsersToAPI(users);\n\n const responseData = formatPaginatedResponse<UserAPI>({\n data: formattedUsers,\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 GetUserByIdParams = { userId: string };\nexport type GetUserByIdResult = ResponseData<UserAPI>;\n\nexport const getUserById = async (\n req: Request<GetUserByIdParams>,\n res: Response<GetUserByIdResult>,\n _next: NextFunction\n): Promise<void> => {\n const { userId } = req.params;\n\n try {\n const user = await userService.getUserById(userId);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({ data: formattedUser });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetUserByEmailParams = { email: string };\nexport type GetUserByEmailResult = ResponseData<UserAPI>;\n\nexport const getUserByEmail = async (\n req: Request<GetUserByEmailParams>,\n res: Response<GetUserByEmailResult>,\n _next: NextFunction\n): Promise<void> => {\n const { email } = req.params;\n const { roles } = res.locals;\n\n try {\n const user = await userService.getUserByEmail(email);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'user:read'\n )({\n ...res.locals,\n targetUserIds: [user.id],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({ data: formattedUser });\n\n res.json(responseData);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type UpdateUserBody = Partial<User>;\nexport type UpdateUserResult = ResponseData<UserAPI>;\n\n/**\n * Updates user information (phone number, date of birth).\n */\nexport const updateUser = async (\n req: Request<any, any, UpdateUserBody | undefined>,\n res: Response<UpdateUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const userData = req.body;\n const { user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (typeof userData !== 'object') {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_DATA_NOT_FOUND');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'user:write'\n )({\n ...res.locals,\n targetUserIds: [user.id],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const updatedUser = await userService.updateUserById(user.id, userData);\n\n logger.info(\n `User updated: Name: ${updatedUser.name}, id: ${String(updatedUser.id)}`\n );\n\n const formattedUser = mapUserToAPI(updatedUser);\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User updated',\n fr: 'Utilisateur mis à jour',\n es: 'Usuario actualizado',\n }),\n description: t({\n en: 'User updated successfully',\n fr: 'Utilisateur mis à jour avec succès',\n es: 'Usuario actualizado con éxito',\n }),\n data: formattedUser,\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 DeleteUserParams = { userId: string };\nexport type DeleteUserResult = ResponseData<UserAPI>;\n\n/**\n * Deletes a user based on the provided ID.\n */\nexport const deleteUser = async (\n req: Request<any, any, DeleteUserParams>,\n res: Response<DeleteUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const { userId } = req.params;\n const { roles } = res.locals;\n\n if (!hasPermission(roles, 'user:admin')()) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const user = await userService.deleteUser(userId);\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User deleted',\n fr: 'Utilisateur supprimé',\n es: 'Usuario eliminado',\n }),\n description: t({\n en: 'User deleted successfully',\n fr: 'Utilisateur supprimé avec succès',\n es: 'Usuario eliminado con éxito',\n }),\n data: formattedUser,\n });\n\n res.json(responseData);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nlet clients: Array<{ id: number; userId: string; res: Response }> = [];\n\nexport const sendVerificationUpdate = (user: User) => {\n const filteredClients = clients.filter(\n (client) => String(client.userId) === String(user.id)\n );\n\n for (const client of filteredClients) {\n if (user.emailVerified) {\n client.res.write(\n `data: ${JSON.stringify({ userId: user.id, status: 'verified' })}\\n\\n`\n );\n }\n }\n};\n\nexport type VerifyEmailStatusSSEParams = { userId: string };\n\n/**\n * SSE to check the email verification status\n */\nexport const verifyEmailStatusSSE = async (\n req: Request<VerifyEmailStatusSSEParams, any, any>,\n res: Response\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 { userId } = req.params; // Get user ID from query parameters\n const clientId = Date.now();\n\n const user = await userService.getUserById(userId);\n\n if (!user) {\n logger.error(`User not found - User ID: ${userId}`);\n res.write(`data: ${JSON.stringify({ userId, status: 'error' })}\\n\\n`);\n res.end();\n return;\n }\n\n // Add client to the list\n const newClient = { id: clientId, userId, res };\n clients.push(newClient);\n\n sendVerificationUpdate(user);\n\n // Remove client on connection close\n req.on('close', () => {\n clients = clients.filter((client) => client.id !== clientId);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,mBAA0B;AAC1B,kBAA6B;AAC7B,oBAA4C;AAE5C,iDAAoD;AAEpD,kBAA4C;AAC5C,yBAA8B;AAC9B,0BAKO;AAEP,8BAAkB;AAQX,MAAM,aAAa,OACxB,KACA,KACA,UACkB;AAClB,QAAM,OAAyB,IAAI;AAEnC,MAAI,CAAC,MAAM;AACT,+BAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AAEA,MAAI;AACF,UAAM,UAAU,MAAM,YAAY,WAAW,IAAI;AAEjD,cAAM,wBAAU;AAAA,MACd,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AE,IAAI,UAAU,QAAQ,IAAI;AAC9C,UAAQ,KAAK,SAAS;AAEtB,yBAAuB,IAAI;AAG3B,MAAI,GAAG,SAAS,MAAM;AACpB,cAAU,QAAQ,OAAO,CAAC,WAAW,OAAO,OAAO,QAAQ;AAAA,EAC7D,CAAC;AACH;","names":["user"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/user.controller.ts"],"sourcesContent":["import type { User, UserAPI } from '@/types/user.types';\nimport { logger } from '@logger';\nimport type { ResponseWithSession } from '@middlewares/sessionAuth.middleware';\nimport { sendEmail } from '@services/email.service';\nimport * as userService from '@services/user.service';\nimport { type AppError, ErrorHandler } from '@utils/errors';\nimport type { FiltersAndPagination } from '@utils/filtersAndPagination/getFiltersAndPaginationFromBody';\nimport { getOrganizationFiltersAndPagination } from '@utils/filtersAndPagination/getOrganizationFiltersAndPagination';\nimport type { UserFiltersParam } from '@utils/filtersAndPagination/getUserFiltersAndPagination';\nimport { mapUsersToAPI, mapUserToAPI } from '@utils/mapper/user';\nimport { hasPermission } from '@utils/permissions';\nimport {\n formatPaginatedResponse,\n formatResponse,\n type PaginatedResponse,\n type ResponseData,\n} from '@utils/responseData';\nimport type { NextFunction, Request } from 'express';\nimport { t } from 'express-intlayer';\n\nexport type CreateUserBody = { email: string; password?: string };\nexport type CreateUserResult = ResponseData<UserAPI>;\n\n/**\n * Creates a new user.\n */\nexport const createUser = async (\n req: Request<any, any, User>,\n res: ResponseWithSession<CreateUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const user: User | undefined = req.body;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n try {\n const newUser = await userService.createUser(user);\n\n await sendEmail({\n type: 'welcome',\n to: newUser.email,\n username: newUser.name,\n loginLink: `${process.env.CLIENT_URL}/auth/login`,\n });\n\n const formattedUser = mapUserToAPI(newUser);\n\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User created',\n fr: 'Utilisateur créé',\n es: 'Usuario creado',\n }),\n description: t({\n en: 'User created successfully',\n fr: 'Utilisateur créé avec succès',\n es: 'Usuario creado con éxito',\n }),\n data: formattedUser,\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 GetUsersParams = FiltersAndPagination<UserFiltersParam>;\nexport type GetUsersResult = PaginatedResponse<UserAPI>;\n\n/**\n * Retrieves a list of users based on filters and pagination.\n */\nexport const getUsers = async (\n req: Request<GetUsersParams>,\n res: ResponseWithSession<GetUsersResult>,\n _next: NextFunction\n): Promise<void> => {\n const { user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n const { filters, pageSize, skip, page, getNumberOfPages } =\n getOrganizationFiltersAndPagination(req);\n\n try {\n const users = await userService.findUsers(filters, skip, pageSize);\n\n if (\n !hasPermission(\n roles,\n 'user:read'\n )({\n ...res.locals,\n targetUsers: users,\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const totalItems = await userService.countUsers(filters);\n\n const formattedUsers = mapUsersToAPI(users);\n\n const responseData = formatPaginatedResponse<UserAPI>({\n data: formattedUsers,\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 GetUserByIdParams = { userId: string };\nexport type GetUserByIdResult = ResponseData<UserAPI>;\n\nexport const getUserById = async (\n req: Request<GetUserByIdParams>,\n res: ResponseWithSession<GetUserByIdResult>,\n _next: NextFunction\n): Promise<void> => {\n const { userId } = req.params;\n\n try {\n const user = await userService.getUserById(userId);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({ data: formattedUser });\n\n res.json(responseData);\n return;\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type GetUserByEmailParams = { email: string };\nexport type GetUserByEmailResult = ResponseData<UserAPI>;\n\nexport const getUserByEmail = async (\n req: Request<GetUserByEmailParams>,\n res: ResponseWithSession<GetUserByEmailResult>,\n _next: NextFunction\n): Promise<void> => {\n const { email } = req.params;\n const { roles } = res.locals;\n\n try {\n const user = await userService.getUserByEmail(email);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'user:read'\n )({\n ...res.locals,\n targetUsers: [user],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({ data: formattedUser });\n\n res.json(responseData);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nexport type UpdateUserBody = Partial<User>;\nexport type UpdateUserResult = ResponseData<UserAPI>;\n\n/**\n * Updates user information (phone number, date of birth).\n */\nexport const updateUser = async (\n req: Request<any, any, UpdateUserBody | undefined>,\n res: ResponseWithSession<UpdateUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const userData = req.body;\n const { user, roles } = res.locals;\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_DEFINED');\n return;\n }\n\n if (typeof userData !== 'object') {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_DATA_NOT_FOUND');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'user:write'\n )({\n ...res.locals,\n targetUsers: [userData as User],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n try {\n const updatedUser = await userService.updateUserById(user.id, userData);\n\n logger.info(\n `User updated: Name: ${updatedUser.name}, id: ${String(updatedUser.id)}`\n );\n\n const formattedUser = mapUserToAPI(updatedUser);\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User updated',\n fr: 'Utilisateur mis à jour',\n es: 'Usuario actualizado',\n }),\n description: t({\n en: 'User updated successfully',\n fr: 'Utilisateur mis à jour avec succès',\n es: 'Usuario actualizado con éxito',\n }),\n data: formattedUser,\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 DeleteUserParams = { userId: string };\nexport type DeleteUserResult = ResponseData<UserAPI>;\n\n/**\n * Deletes a user based on the provided ID.\n */\nexport const deleteUser = async (\n req: Request<DeleteUserParams>,\n res: ResponseWithSession<DeleteUserResult>,\n _next: NextFunction\n): Promise<void> => {\n const { userId } = req.params;\n const { roles } = res.locals;\n\n try {\n const user = await userService.getUserById(userId);\n\n if (!user) {\n ErrorHandler.handleGenericErrorResponse(res, 'USER_NOT_FOUND');\n return;\n }\n\n if (\n !hasPermission(\n roles,\n 'user:admin'\n )({\n ...res.locals,\n targetUsers: [user],\n })\n ) {\n ErrorHandler.handleGenericErrorResponse(res, 'PERMISSION_DENIED');\n return;\n }\n\n await userService.deleteUser(userId);\n\n const formattedUser = mapUserToAPI(user);\n const responseData = formatResponse<UserAPI>({\n message: t({\n en: 'User deleted',\n fr: 'Utilisateur supprimé',\n es: 'Usuario eliminado',\n }),\n description: t({\n en: 'User deleted successfully',\n fr: 'Utilisateur supprimé avec succès',\n es: 'Usuario eliminado con éxito',\n }),\n data: formattedUser,\n });\n\n res.json(responseData);\n } catch (error) {\n ErrorHandler.handleAppErrorResponse(res, error as AppError);\n return;\n }\n};\n\nlet clients: Array<{ id: number; userId: string; res: ResponseWithSession }> =\n [];\n\nexport const sendVerificationUpdate = (user: User) => {\n const filteredClients = clients.filter(\n (client) => String(client.userId) === String(user.id)\n );\n\n for (const client of filteredClients) {\n if (user.emailVerified) {\n client.res.write(\n `data: ${JSON.stringify({ userId: user.id, status: 'verified' })}\\n\\n`\n );\n }\n }\n};\n\nexport type VerifyEmailStatusSSEParams = { userId: string };\n\n/**\n * SSE to check the email verification status\n */\nexport const verifyEmailStatusSSE = async (\n req: Request<VerifyEmailStatusSSEParams, any, any>,\n res: ResponseWithSession\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 { userId } = req.params; // Get user ID from query parameters\n const clientId = Date.now();\n\n const user = await userService.getUserById(userId);\n\n if (!user) {\n logger.error(`User not found - User ID: ${userId}`);\n res.write(`data: ${JSON.stringify({ userId, status: 'error' })}\\n\\n`);\n res.end();\n return;\n }\n\n // Add client to the list\n const newClient = { id: clientId, userId, res };\n clients.push(newClient);\n\n sendVerificationUpdate(user);\n\n // Remove client on connection close\n req.on('close', () => {\n clients = clients.filter((client) => client.id !== clientId);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AAEvB,mBAA0B;AAC1B,kBAA6B;AAC7B,oBAA4C;AAE5C,iDAAoD;AAEpD,kBAA4C;AAC5C,yBAA8B;AAC9B,0BAKO;AAEP,8BAAkB;AAQX,MAAM,aAAa,OACxB,KACA,KACA,UACkB;AAClB,QAAM,OAAyB,IAAI;AAEnC,MAAI,CAAC,MAAM;AACT,+BAAa,2BAA2B,KAAK,kBAAkB;AAC/D;AAAA,EACF;AAEA,MAAI;AACF,UAAM,UAAU,MAAM,YAAY,WAAW,IAAI;AAEjD,cAAM,wBAAU;AAAA,MACd,MAAM;AAAA,MACN,IAAI,QAAQ;AAAA,MACZ,UAAU,QAAQ;AAAA,MAClB,W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AAAA,CAAM;AACpE,QAAI,IAAI;AACR;AAAA,EACF;AAGA,QAAM,YAAY,EAAE,IAAI,UAAU,QAAQ,IAAI;AAC9C,UAAQ,KAAK,SAAS;AAEtB,yBAAuB,IAAI;AAG3B,MAAI,GAAG,SAAS,MAAM;AACpB,cAAU,QAAQ,OAAO,CAAC,WAAW,OAAO,OAAO,QAAQ;AAAA,EAC7D,CAAC;AACH;","names":[]}
|
|
@@ -33,7 +33,7 @@ const OAuthTokenCreatedEmailEN = ({
|
|
|
33
33
|
securityLogUrl,
|
|
34
34
|
supportUrl
|
|
35
35
|
}) => {
|
|
36
|
-
const previewText = `A third-party OAuth
|
|
36
|
+
const previewText = `A third-party OAuth access key has been added to your Intlayer account`;
|
|
37
37
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.Html, { children: [
|
|
38
38
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Head, {}),
|
|
39
39
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Preview, { children: previewText }),
|
|
@@ -48,19 +48,17 @@ const OAuthTokenCreatedEmailEN = ({
|
|
|
48
48
|
className: "mx-auto my-0"
|
|
49
49
|
}
|
|
50
50
|
) }),
|
|
51
|
-
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Heading, { className: "mx-0 my-[30px] p-0 text-center text-[24px] font-normal text-black", children: "A third-party OAuth
|
|
51
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Heading, { className: "mx-0 my-[30px] p-0 text-center text-[24px] font-normal text-black", children: "A third-party OAuth access key has been added to your account" }),
|
|
52
52
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.Text, { className: "text-[14px] leading-[24px] text-black", children: [
|
|
53
53
|
"Hey ",
|
|
54
54
|
username,
|
|
55
55
|
"!"
|
|
56
56
|
] }),
|
|
57
57
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.Text, { className: "text-[14px] leading-[24px] text-black", children: [
|
|
58
|
-
"A third-party OAuth
|
|
58
|
+
"A third-party OAuth access key (",
|
|
59
59
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: applicationName }),
|
|
60
|
-
") with ",
|
|
61
|
-
scopes.
|
|
62
|
-
" ",
|
|
63
|
-
"scopes was recently authorized to access your account."
|
|
60
|
+
") with the following permissions was recently authorized to access your account:",
|
|
61
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { children: scopes.map((scope) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: scope }, scope)) })
|
|
64
62
|
] }),
|
|
65
63
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Section, { className: "my-[32px] text-center", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
66
64
|
import_components.Button,
|