arkos 1.3.8-canary.8 → 1.3.9-beta

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.
Files changed (58) hide show
  1. package/cli.js +2 -5
  2. package/dist/cjs/modules/auth/auth.controller.js +7 -7
  3. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  4. package/dist/cjs/modules/auth/auth.service.js +4 -4
  5. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  6. package/dist/cjs/modules/error-handler/error-handler.controller.js +3 -4
  7. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  8. package/dist/cjs/modules/file-upload/file-upload.controller.js +4 -4
  9. package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
  10. package/dist/cjs/modules/file-upload/file-upload.service.js +6 -9
  11. package/dist/cjs/modules/file-upload/file-upload.service.js.map +1 -1
  12. package/dist/cjs/modules/file-upload/utils/helpers/file-upload.helpers.js +6 -2
  13. package/dist/cjs/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -1
  14. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  15. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
  16. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  17. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  18. package/dist/cjs/utils/cli/build.js +3 -2
  19. package/dist/cjs/utils/cli/build.js.map +1 -1
  20. package/dist/cjs/utils/cli/start.js +1 -0
  21. package/dist/cjs/utils/cli/start.js.map +1 -1
  22. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  23. package/dist/cjs/utils/dotenv.helpers.js +2 -1
  24. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  25. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +1 -12
  26. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  27. package/dist/cjs/utils/prisma/prisma-schema-parser.js +3 -4
  28. package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
  29. package/dist/esm/modules/auth/auth.controller.js +7 -7
  30. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  31. package/dist/esm/modules/auth/auth.service.js +4 -4
  32. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  33. package/dist/esm/modules/error-handler/error-handler.controller.js +3 -4
  34. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  35. package/dist/esm/modules/file-upload/file-upload.controller.js +4 -4
  36. package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
  37. package/dist/esm/modules/file-upload/file-upload.service.js +6 -9
  38. package/dist/esm/modules/file-upload/file-upload.service.js.map +1 -1
  39. package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js +6 -2
  40. package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -1
  41. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  42. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
  43. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  44. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  45. package/dist/esm/utils/cli/build.js +3 -2
  46. package/dist/esm/utils/cli/build.js.map +1 -1
  47. package/dist/esm/utils/cli/start.js +1 -0
  48. package/dist/esm/utils/cli/start.js.map +1 -1
  49. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  50. package/dist/esm/utils/dotenv.helpers.js +2 -1
  51. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  52. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +1 -12
  53. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  54. package/dist/esm/utils/prisma/prisma-schema-parser.js +3 -4
  55. package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
  56. package/dist/types/modules/file-upload/file-upload.service.d.ts +2 -2
  57. package/dist/types/modules/file-upload/utils/helpers/file-upload.helpers.d.ts +1 -1
  58. package/package.json +1 -1
package/cli.js CHANGED
@@ -16,11 +16,8 @@
16
16
  console.error("Error checking package.json:", err);
17
17
  }
18
18
 
19
- if (useEsm) {
20
- await import("./dist/esm/utils/cli/index.js");
21
- } else {
22
- await import("./dist/cjs/utils/cli/index.js");
23
- }
19
+ if (useEsm) await import("./dist/esm/utils/cli/index.js");
20
+ else await import("./dist/cjs/utils/cli/index.js");
24
21
  } catch (err) {
25
22
  console.error("Failed to load CLI:", err);
26
23
  process.exit(1);
@@ -76,7 +76,7 @@ const authControllerFactory = async (interceptors = {}) => {
76
76
  const usernameValue = req.body[lastField];
77
77
  const { password } = req.body;
78
78
  if (!usernameValue || !password)
79
- return next(new app_error_1.default(`Please provide both ${lastField} and password`, 400));
79
+ return next(new app_error_1.default(`Please provide both ${lastField} and password`, 400, `MissingCredentialFields`));
80
80
  let whereClause;
81
81
  if (usernameField?.includes?.(".")) {
82
82
  const valueToFind = (0, auth_controller_helpers_1.getNestedValue)(req.body, usernameField);
@@ -91,7 +91,7 @@ const authControllerFactory = async (interceptors = {}) => {
91
91
  const user = (await userService.findOne(whereClause, req.prismaQueryOptions || {}));
92
92
  if (!user ||
93
93
  !(await auth_service_1.default.isCorrectPassword(password, user.password))) {
94
- return next(new app_error_1.default(`Incorrect ${lastField} or password`, 401));
94
+ return next(new app_error_1.default(`Incorrect ${lastField} or password`, 401, `IncorrectCredentials`));
95
95
  }
96
96
  const token = auth_service_1.default.signJwtToken(user.id);
97
97
  const cookieOptions = auth_service_1.default.getJwtCookieOptions(req);
@@ -165,7 +165,7 @@ const authControllerFactory = async (interceptors = {}) => {
165
165
  updatePassword: (0, catch_async_1.default)(async (req, res, next) => {
166
166
  const { currentPassword, newPassword } = req.body;
167
167
  if (!currentPassword || !newPassword)
168
- return next(new app_error_1.default("currentPassword and newPassword are required", 400));
168
+ return next(new app_error_1.default("currentPassword and newPassword are required", 400, "SameCurrentAndNewPassword"));
169
169
  const user = req.user;
170
170
  if (!user || user?.isActive === false || user?.deletedSelfAccountAt)
171
171
  return next(new app_error_1.default("User not found!", 404));
@@ -173,11 +173,11 @@ const authControllerFactory = async (interceptors = {}) => {
173
173
  const configs = (0, server_1.getArkosConfig)();
174
174
  const initAuthConfigs = configs?.authentication;
175
175
  if (!isPasswordCorrect)
176
- return next(new app_error_1.default("Current password is incorrect.", 400));
176
+ return next(new app_error_1.default("Current password is incorrect", 400, "IncorrentCurrentPassword"));
177
177
  if (!auth_service_1.default.isPasswordStrong(String(newPassword)) &&
178
178
  !configs?.validation) {
179
179
  return next(new app_error_1.default(initAuthConfigs?.passwordValidation?.message ||
180
- "The new password must contain at least one uppercase letter, one lowercase letter, and one number", 400));
180
+ "The new password must contain at least one uppercase letter, one lowercase letter, and one number", 400, "PasswordDoesNotMeetRequirements"));
181
181
  }
182
182
  await userService.updateOne({ id: user.id }, {
183
183
  password: await auth_service_1.default.hashPassword(newPassword),
@@ -216,7 +216,7 @@ const authControllerFactory = async (interceptors = {}) => {
216
216
  const arkosConfig = (0, server_1.getArkosConfig)();
217
217
  const resourceName = req.params?.resourceName;
218
218
  if (!resourceName)
219
- throw new app_error_1.default(`Please provide a resoureName`, 400);
219
+ throw new app_error_1.default(`Please provide a resoureName`, 400, "MissiongResourseName");
220
220
  const authActions = auth_action_service_1.default
221
221
  .getByResource(req.params?.resourceName)
222
222
  ?.map((authAction) => {
@@ -225,7 +225,7 @@ const authControllerFactory = async (interceptors = {}) => {
225
225
  return authAction;
226
226
  });
227
227
  if (!authActions)
228
- throw new app_error_1.default(`No auth action with resource name ${resourceName}`, 404);
228
+ throw new app_error_1.default(`No auth action with resource name ${resourceName}`, 404, "AuthActionNotFound");
229
229
  res.json({
230
230
  total: authActions.length,
231
231
  results: authActions.length,
@@ -1 +1 @@
1
- {"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":";;;;;;AAAA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Y,CAAC;YAE9C,IAAI,CAAC,YAAY;gBACf,MAAM,IAAI,mBAAQ,CAAC,8BAA8B,EAAE,GAAG,CAAC,CAAC;YAE1D,MAAM,WAAW,GAAG,6BAAiB;iBAClC,aAAa,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;gBACxC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;gBACnB,IAAI,WAAW,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS;oBACjD,OAAQ,UAAkB,EAAE,KAAK,CAAC;gBACpC,OAAO,UAAU,CAAC;YACpB,CAAC,CAAC,CAAC;YAEL,IAAI,CAAC,WAAW;gBACd,MAAM,IAAI,mBAAQ,CAChB,qCAAqC,YAAY,EAAE,EACnD,GAAG,CACJ,CAAC;YAEJ,GAAG,CAAC,IAAI,CAAC;gBACP,KAAK,EAAE,WAAW,CAAC,MAAM;gBACzB,OAAO,EAAE,WAAW,CAAC,MAAM;gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC;AA9YW,QAAA,qBAAqB,yBA8YhC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { BaseService } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n} from \"./utils/helpers/auth.controller.helpers\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable interceptors\n *\n * @param interceptors - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (interceptors: any = {}) => {\n const userService = new BaseService(\"user\");\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterGetMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"InvalidFieldPassword\"\n );\n\n const user = (await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterUpdateMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (interceptors?.afterLogout) {\n (res as any).originalData = null;\n req.responseData = null;\n res.locals.data = null;\n (res as any).originalStatus = 204;\n req.responseStatus = 204;\n res.locals.status = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n *\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(`Please provide both ${lastField} and password`, 400)\n );\n\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n whereClause = { [usernameField]: usernameValue };\n }\n\n const user = (await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(new AppError(`Incorrect ${lastField} or password`, 401));\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions = authService.getJwtCookieOptions(req);\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n res.locals.data = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n req.accessToken = token;\n\n if (interceptors?.afterLogin) {\n (res as any).originalData = req.responseData;\n req.additionalData = { user };\n res.locals.additional = { user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterSignup) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 201;\n req.responseStatus = 201;\n res.locals.status = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id;\n\n const updatedUser = (await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterDeleteMe) {\n (res as any).originalData = { data: updatedUser };\n req.responseData = { data: updatedUser };\n res.locals.data = { data: updatedUser };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\"currentPassword and newPassword are required\", 400)\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n // Check if the current password is correct\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n\n if (!isPasswordCorrect)\n return next(new AppError(\"Current password is incorrect.\", 400));\n\n // Check password strength (optional but recommended)\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400\n )\n );\n }\n\n // Update the password\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n const responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n\n if (interceptors?.afterUpdatePassword) {\n (res as any).originalData = responseData;\n req.additionalData = { user };\n req.responseData = responseData;\n res.locals.data = responseData;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(responseData);\n }\n ),\n\n findManyAuthAction: catchAsync(\n async (_: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const authActions = authActionService.getAll()?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n\n findOneAuthAction: catchAsync(\n async (req: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const resourceName = req.params?.resourceName;\n\n if (!resourceName)\n throw new AppError(`Please provide a resoureName`, 400);\n\n const authActions = authActionService\n .getByResource(req.params?.resourceName)\n ?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n if (!authActions)\n throw new AppError(\n `No auth action with resource name ${resourceName}`,\n 404\n );\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n };\n};\n"]}
1
+ {"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":";;;;;;AAAA,qFAA4D;AAC5D,iFAAwD;AAExD,kEAAyC;AACzC,uDAAmD;AAEnD,yCAA8C;AAC9C,qFAIiD;AACjD,+FAAqE;AAKxD,QAAA,yBAAyB,GAAG;IACvC,QAAQ,EAAE,KAAK;CAChB,CAAC;AAQK,MAAM,qBAAqB,GAAG,KAAK,EAAE,eAAoB,EAAE,EAAE,EAAE;IACpE,MAAM,WAAW,GAAG,IAAI,0BAAW,CAAC,MAAM,CAAC,CAAC;IAE5C,OAAO;QAIL,KAAK,EAAE,IAAA,qBAAU,EACf,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;YACF,MAAM,IAAI,GAAG,CAAC,MAAM,WAAW,CAAC,OAAO,CACrC,EAAE,EAAE,EAAE,GAAG,CAAC,IAAK,CAAC,EAAE,EAAE,EACpB,GAAG,CAAC,kBAAkB,IAAI,EAAE,CAC7B,CAAwB,CAAC;YAE1B,MAAM,CAAC,IAAI,CAAC,iCAAyB,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;gBACrD,IAAI,IAAI;oBAAE,OAAO,IAAI,CAAC,GAAiB,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;YAEH,IAAI,YAAY,EAAE,UAAU,EAAE,CAAC;gBAC5B,GAAW,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;gBAC3C,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,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OAAO,UAAU,CAAC;YACpB,CAAC,CAAC,CAAC;YAEH,GAAG,CAAC,IAAI,CAAC;gBACP,KAAK,EAAE,WAAW,CAAC,MAAM;gBACzB,OAAO,EAAE,WAAW,CAAC,MAAM;gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;QAED,iBAAiB,EAAE,IAAA,qBAAU,EAC3B,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,EAAE;YAC9C,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,MAAM,YAAY,GAAG,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;YAE9C,IAAI,CAAC,YAAY;gBACf,MAAM,IAAI,mBAAQ,CAChB,8BAA8B,EAC9B,GAAG,EACH,sBAAsB,CACvB,CAAC;YAEJ,MAAM,WAAW,GAAG,6BAAiB;iBAClC,aAAa,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;gBACxC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;gBACnB,IAAI,WAAW,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS;oBACjD,OAAQ,UAAkB,EAAE,KAAK,CAAC;gBACpC,OAAO,UAAU,CAAC;YACpB,CAAC,CAAC,CAAC;YAEL,IAAI,CAAC,WAAW;gBACd,MAAM,IAAI,mBAAQ,CAChB,qCAAqC,YAAY,EAAE,EACnD,GAAG,EACH,oBAAoB,CACrB,CAAC;YAEJ,GAAG,CAAC,IAAI,CAAC;gBACP,KAAK,EAAE,WAAW,CAAC,MAAM;gBACzB,OAAO,EAAE,WAAW,CAAC,MAAM;gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC;AAraW,QAAA,qBAAqB,yBAqahC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { BaseService } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n} from \"./utils/helpers/auth.controller.helpers\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable interceptors\n *\n * @param interceptors - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (interceptors: any = {}) => {\n const userService = new BaseService(\"user\");\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterGetMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"InvalidFieldPassword\"\n );\n\n const user = (await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterUpdateMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (interceptors?.afterLogout) {\n (res as any).originalData = null;\n req.responseData = null;\n res.locals.data = null;\n (res as any).originalStatus = 204;\n req.responseStatus = 204;\n res.locals.status = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n *\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(\n `Please provide both ${lastField} and password`,\n 400,\n `MissingCredentialFields`\n )\n );\n\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n whereClause = { [usernameField]: usernameValue };\n }\n\n const user = (await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(\n new AppError(\n `Incorrect ${lastField} or password`,\n 401,\n `IncorrectCredentials`\n )\n );\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions = authService.getJwtCookieOptions(req);\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n res.locals.data = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n req.accessToken = token;\n\n if (interceptors?.afterLogin) {\n (res as any).originalData = req.responseData;\n req.additionalData = { user };\n res.locals.additional = { user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterSignup) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 201;\n req.responseStatus = 201;\n res.locals.status = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id;\n\n const updatedUser = (await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterDeleteMe) {\n (res as any).originalData = { data: updatedUser };\n req.responseData = { data: updatedUser };\n res.locals.data = { data: updatedUser };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\n \"currentPassword and newPassword are required\",\n 400,\n \"SameCurrentAndNewPassword\"\n )\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n\n if (!isPasswordCorrect)\n return next(\n new AppError(\n \"Current password is incorrect\",\n 400,\n \"IncorrentCurrentPassword\"\n )\n );\n\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400,\n \"PasswordDoesNotMeetRequirements\"\n )\n );\n }\n\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n const responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n\n if (interceptors?.afterUpdatePassword) {\n (res as any).originalData = responseData;\n req.additionalData = { user };\n req.responseData = responseData;\n res.locals.data = responseData;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(responseData);\n }\n ),\n\n findManyAuthAction: catchAsync(\n async (_: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const authActions = authActionService.getAll()?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n\n findOneAuthAction: catchAsync(\n async (req: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const resourceName = req.params?.resourceName;\n\n if (!resourceName)\n throw new AppError(\n `Please provide a resoureName`,\n 400,\n \"MissiongResourseName\"\n );\n\n const authActions = authActionService\n .getByResource(req.params?.resourceName)\n ?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n if (!authActions)\n throw new AppError(\n `No auth action with resource name ${resourceName}`,\n 404,\n \"AuthActionNotFound\"\n );\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n };\n};\n"]}
@@ -32,10 +32,10 @@ class AuthService {
32
32
  }
33
33
  signJwtToken(id, expiresIn, secret) {
34
34
  const { authentication: configs } = (0, server_1.getArkosConfig)();
35
- if (process.env.NODE_ENV === "production" &&
35
+ if (process.env.ARKOS_BUILD === "true" &&
36
36
  !process.env.JWT_SECRET &&
37
37
  !configs?.jwt?.secret)
38
- throw new app_error_1.default("Missing JWT secret on production!", 500, {}, "MissingJWTOnProduction");
38
+ throw new app_error_1.default("Missing JWT secret on production!", 500, "MissingJWTOnProduction");
39
39
  secret =
40
40
  secret ||
41
41
  configs?.jwt?.secret ||
@@ -99,10 +99,10 @@ class AuthService {
99
99
  }
100
100
  async verifyJwtToken(token, secret) {
101
101
  const { authentication: configs } = (0, server_1.getArkosConfig)();
102
- if (process.env.NODE_ENV === "production" &&
102
+ if (process.env.ARKOS_BUILD === "true" &&
103
103
  !process.env.JWT_SECRET &&
104
104
  !configs?.jwt?.secret)
105
- throw new app_error_1.default("Missing JWT secret!", 500);
105
+ throw new app_error_1.default("Missing JWT secret in production", 500, "MissingJWTSecretInProduction");
106
106
  secret =
107
107
  secret ||
108
108
  configs?.jwt?.secret ||
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AAMrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAyarD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAqFJ,CAAC;IA/fC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;YACrC,CAAC,OAAO,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,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AA7gBD,kCA6gBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport { CookieOptions } from \"express\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AAKrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,GAAG,IAAA,uBAAc,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QAEvD,OAAO,KAAK,EAAE,IAAyB,EAAoB,EAAE;YAE3D,MAAM,OAAO,GAAG,IAAA,uBAAc,GAAE,CAAC;YACjC,IAAI,CAAC,OAAO,EAAE,cAAc;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,CAAC,WAAW;gBAAE,OAAO,IAAI,CAAC;YAElC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAhhBD,kCAghBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -45,7 +45,7 @@ function errorHandler(err, req, res, _) {
45
45
  message: err.message,
46
46
  stack: err?.stack || undefined,
47
47
  };
48
- if (process.env.NODE_ENV == "production")
48
+ if (process.env.ARKOS_BUILD === "true")
49
49
  delete error?.stack;
50
50
  if (err.name === "JsonWebTokenError")
51
51
  error = errorControllerHelper.handleJWTError();
@@ -85,7 +85,7 @@ function errorHandler(err, req, res, _) {
85
85
  error = errorControllerHelper.handleVersionMismatchError(err);
86
86
  if (err.name === "NetworkError")
87
87
  error = errorControllerHelper.handleNetworkError(err);
88
- if (process.env.NODE_ENV !== "production")
88
+ if (process.env.ARKOS_BUILD !== "true")
89
89
  return sendDevelopmentError({
90
90
  ...error,
91
91
  message: error.message,
@@ -139,8 +139,7 @@ function sendProductionError(err, req, res) {
139
139
  });
140
140
  }
141
141
  process.on("SIGTERM", () => {
142
- if (process.env.NODE_ENV !== "production" &&
143
- process.env.NODE_ENV !== "staging") {
142
+ if (process.env.ARKOS_BUILD !== "true") {
144
143
  process.exit();
145
144
  }
146
145
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,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aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,G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AC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -53,7 +53,7 @@ class FileUploadController {
53
53
  let data;
54
54
  if (req.files && Array.isArray(req.files) && req.files.length > 0) {
55
55
  if (fileType === "images") {
56
- data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processImage)(req, file.path, options)));
56
+ data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processImage)(req, next, file.path, options)));
57
57
  }
58
58
  else {
59
59
  data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processFile)(req, file.path)));
@@ -62,7 +62,7 @@ class FileUploadController {
62
62
  }
63
63
  else if (req.file) {
64
64
  if (fileType === "images") {
65
- data = await (0, file_upload_helpers_1.processImage)(req, req.file.path, options);
65
+ data = await (0, file_upload_helpers_1.processImage)(req, next, req.file.path, options);
66
66
  }
67
67
  else {
68
68
  data = await (0, file_upload_helpers_1.processFile)(req, req.file.path);
@@ -197,7 +197,7 @@ class FileUploadController {
197
197
  let data;
198
198
  if (req.files && Array.isArray(req.files) && req.files.length > 0) {
199
199
  if (fileType === "images") {
200
- data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processImage)(req, file.path, options)));
200
+ data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processImage)(req, next, file.path, options)));
201
201
  }
202
202
  else {
203
203
  data = await Promise.all(req.files.map((file) => (0, file_upload_helpers_1.processFile)(req, file.path)));
@@ -206,7 +206,7 @@ class FileUploadController {
206
206
  }
207
207
  else if (req.file) {
208
208
  if (fileType === "images") {
209
- data = await (0, file_upload_helpers_1.processImage)(req, req.file.path, options);
209
+ data = await (0, file_upload_helpers_1.processImage)(req, next, req.file.path, options);
210
210
  }
211
211
  else {
212
212
  data = await (0, file_upload_helpers_1.processFile)(req, req.file.path);
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAa,oBAAoB;IAAjC;QAeE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,IAAA,oCAAmB,EAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;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B,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAhYD,oDAgYC;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(new AppError(\"No file uploaded\", 400));\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // This checks if the URL follows the expected format: /api/files/{fileType}/{fileName}\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n // URL matches expected pattern, use deleteFileByUrl\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n // Handle different types of errors\n if (error instanceof AppError) {\n return next(error);\n }\n // File doesn't exist or other error\n return next(new AppError(\"File not found\", 404));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Check if new file was uploaded\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n ) {\n return next(new AppError(\"No new file uploaded\", 400));\n }\n\n // Only attempt to delete old file if fileName is specified\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Check if the URL follows the expected format\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // URL matches expected pattern, use deleteFileByUrl\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n // Log the error but continue with upload - old file might not exist\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n // Process the new uploaded file(s)\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
1
+ {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAa,oBAAoB;IAAjC;QAeE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,IAAA,oCAAmB,EAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,IAAA,2CAAqB,GAAE,CAAC;YAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;YACxC,MAAM,aAAa,GAAG,UAAU,EAAE,aAAa,IAAI,UAAU,CAAC;YAE9D,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,a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AAC;gBAED,MAAM,WAAW,GAAG;oBAClB,OAAO,EAAE,IAAI;oBACb,IAAI;oBACJ,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;wBAC1B,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,8BAA8B,IAAI,CAAC,MAAM,qBAAqB;4BAChE,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,8BAA8B;wBAChD,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,2BAA2B;4BAC7B,CAAC,CAAC,4BAA4B;iBACnC,CAAC;gBAEF,IAAI,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,CAAC;oBACrC,GAAW,CAAC,YAAY,GAAG,WAAW,CAAC;oBACxC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;oBAC7B,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AApYD,oDAoYC;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(new AppError(\"No file uploaded\", 400));\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // This checks if the URL follows the expected format: /api/files/{fileType}/{fileName}\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n // URL matches expected pattern, use deleteFileByUrl\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n // Handle different types of errors\n if (error instanceof AppError) {\n return next(error);\n }\n // File doesn't exist or other error\n return next(new AppError(\"File not found\", 404));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Check if new file was uploaded\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n ) {\n return next(new AppError(\"No new file uploaded\", 400));\n }\n\n // Only attempt to delete old file if fileName is specified\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Check if the URL follows the expected format\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // URL matches expected pattern, use deleteFileByUrl\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n // Log the error but continue with upload - old file might not exist\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n // Process the new uploaded file(s)\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}