arkos 1.4.0-canary.45 → 1.4.0-canary.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/auth/auth.controller.js +1 -1
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +4 -4
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +3 -4
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +3 -2
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +1 -0
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/dotenv.helpers.js +2 -1
- package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +1 -12
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/modules/auth/auth.controller.js +1 -1
- package/dist/esm/modules/auth/auth.controller.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +4 -4
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +3 -4
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/esm/utils/cli/build.js +3 -2
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/start.js +1 -0
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/dotenv.helpers.js +2 -1
- package/dist/esm/utils/dotenv.helpers.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +1 -12
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/package.json +1 -1
|
@@ -177,7 +177,7 @@ const authControllerFactory = async (interceptors = {}) => {
|
|
|
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),
|
|
@@ -1 +1 @@
|
|
|
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,E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E,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 \"PasswordDotNotMeetRequirements\"\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"]}
|
|
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,EAAE,IAAI,EAAE,CAAC;gBAClC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;g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AM;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.
|
|
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,
|
|
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.
|
|
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
|
|
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,KA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E,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;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;YAC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AE,QAAQ,EAAE,aAAa,CAAC,CAAC;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.
|
|
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.
|
|
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.
|
|
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,GAA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M,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,gDAAgD;gBACzD,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,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?.originalError?.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,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C,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,IAAI,OAAO,CAAC,GAAG,CAAC,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?.originalError?.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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAkBA,
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAkBA,4CA0DC;AA5ED,qCAAiC;AACjC,kEAAyC;AAEzC,4FAA6D;AAC7D,mFAGgD;AAChD,oHAAwF;AACxF,8GAAkF;AAClF,uEAAyF;AACzF,uIAA4G;AAC5G,2DAAkE;AAElE,0HAA6F;AAE7F,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAExB,KAAK,UAAU,gBAAgB,CACpC,WAAwB,EACxB,GAAoB;IAEpB,IAAI,CAAC,kBAAkB,EAAE,kBAAkB,EAAE,2BAA2B,CAAC,GACvE,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,MAAM,IAAA,0DAAiC,EAAC,WAAW,CAAC;QACpD,MAAM,IAAA,+CAAsB,EAAC,WAAW,CAAC;QACzC,MAAM,IAAA,qCAAsB,EAAC,GAAG,CAAC;KAClC,CAAC,CAAC;IAEL,MAAM,sBAAsB,GAAG,IAAA,2CAA4B,EAAC,WAAW,CAAC,CAAC;IAEzE,MAAM,kBAAkB,GACtB,MAAM,wCAA0B,CAAC,0BAA0B,CACzD,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,CACZ,CAAC;IAEJ,kBAAkB,GAAG;QACnB,GAAG,kBAAkB;QACrB,GAAG,kBAAkB;QACrB,GAAG,IAAA,sCAAyB,EAAC,WAAW,CAAC;KAC1C,CAAC;IAEF,MAAM,cAAc,GAAG,IAAA,0BAAS,EAC9B,CAAC,MAAM,IAAA,qCAAuB,EAC5B;QACE,GAAG,kBAAkB;QACrB,GAAG,sBAAsB;QACzB,GAAG,2BAA2B;KAC/B,EACD,kBAAkB,CACnB,CAAC,IAAI,EAAE,EACR,WAAW,CAAC,OAAO,IAAI,EAAE,CACA,CAAC;IAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,GAAG,cAAc,EAAE,OAAQ,CAAC;IAE5D,MAAM,oBAAoB,GAAG,IAAA,uBAAY,EAAC;QACxC,UAAU,EAAE,UAA4C;QACxD,GAAG,OAAO;KACX,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,MAAM,IAAA,oDAAmC,EACtD,+BAA+B,CAChC,CAAC;IAEF,aAAa,CAAC,GAAG,CACf,cAAe,CAAC,QAAS,EACzB,MAAM,CAAC,YAAY,CAAC;QAClB,OAAO,EAAE,oBAAoB;QAC7B,GAAG,cAAc,EAAE,+BAA+B;KACnD,CAAC,CACH,CAAC;IAEF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n generatePathsForModels,\n getOpenAPIJsonSchemasByConfigMode,\n} from \"./utils/helpers/swagger.router.helpers\";\nimport missingJsonSchemaGenerator from \"./utils/helpers/missing-json-schemas-generator\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport generateSystemJsonSchemas from \"./utils/helpers/json-schema-generators/generate-system-json-schemas\";\nimport { generateOpenAPIFromApp } from \"../../utils/arkos-router\";\nimport express from \"express\";\nimport getFileUploadJsonSchemaPaths from \"./utils/helpers/get-file-upload-json-schema-paths\";\n\nconst swaggerRouter = Router();\n\nexport async function getSwaggerRouter(\n arkosConfig: ArkosConfig,\n app: express.Express\n): Promise<Router> {\n let [defaultJsonSchemas, defaultModelsPaths, pathsFromCustomArkosRouters] =\n await Promise.all([\n await getOpenAPIJsonSchemasByConfigMode(arkosConfig),\n await generatePathsForModels(arkosConfig),\n await generateOpenAPIFromApp(app),\n ]);\n\n const fileUploadDefaultPaths = getFileUploadJsonSchemaPaths(arkosConfig);\n\n const missingJsonSchemas =\n await missingJsonSchemaGenerator.generateMissingJsonSchemas(\n defaultModelsPaths,\n defaultJsonSchemas,\n arkosConfig\n );\n\n defaultJsonSchemas = {\n ...defaultJsonSchemas,\n ...missingJsonSchemas,\n ...generateSystemJsonSchemas(arkosConfig),\n };\n\n const swaggerConfigs = deepmerge(\n (await getSwaggerDefaultConfig(\n {\n ...defaultModelsPaths,\n ...fileUploadDefaultPaths,\n ...pathsFromCustomArkosRouters,\n },\n defaultJsonSchemas\n )) || {},\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n const { definition, ...options } = swaggerConfigs?.options!;\n\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const scalar = await importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n );\n\n swaggerRouter.use(\n swaggerConfigs!.endpoint!,\n scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n })\n );\n\n return swaggerRouter;\n}\n"]}
|
|
@@ -168,12 +168,10 @@ class MissingJsonSchemasGenerator {
|
|
|
168
168
|
mappedKey = "UpdatePasswordSchema";
|
|
169
169
|
}
|
|
170
170
|
else {
|
|
171
|
-
if (key.includes("ModelSchema"))
|
|
171
|
+
if (key.includes("ModelSchema"))
|
|
172
172
|
mappedKey = key;
|
|
173
|
-
|
|
174
|
-
else {
|
|
173
|
+
else
|
|
175
174
|
mappedKey = `${key}ModelSchema`;
|
|
176
|
-
}
|
|
177
175
|
}
|
|
178
176
|
missingSchemas[mappedKey] = schema;
|
|
179
177
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":";;;;;AAEA,yHAA8F;AAC9F,yCAAqC;AAKrC,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3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\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport { singular } from \"pluralize\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n // Extract all schema references with their context (operationId, method, path)\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n // Group missing schemas by model and collect required actions\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n // Check if schema already exists\n if (currentJsonSchemas[schemaName]) continue;\n\n // Only process ModelSchema references\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // First try to get model and action from operationId (more reliable)\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref analysis if operationId didn't work\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await PrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n // Map generated schemas to the expected naming convention\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n // Handle auth schemas\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n // Handle model schemas - ensure they match the expected naming pattern\n if (key.includes(\"ModelSchema\")) {\n mappedKey = key;\n } else {\n // Add ModelSchema suffix if missing\n mappedKey = `${key}ModelSchema`;\n }\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // FIXME: check if all models are being generarted if so simply keep the error ssilent\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
|
|
1
|
+
{"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":";;;;;AAEA,yHAA8F;AAC9F,yCAAqC;AAKrC,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3B,+GAA+G,CAChH,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEzB,IACE,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM;gBAClC,SAAS,CAAC,WAAW,EAAE,KAAK,OAAO;gBACnC,SAAS,CAAC,WAAW,EAAE,KAAK,QAAQ;gBACpC,SAAS,CAAC,WAAW,EAAE,KAAK,OAAO;gBACnC,SAAS,CAAC,WAAW,EAAE,KAAK,UAAU;gBACtC,SAAS,CAAC,WAAW,EAAE,KAAK,gBAAgB,EAC5C,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IASO,4BAA4B,CAAC,WAAmB;QACtD,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAE9B,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC5D,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC5D,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC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YAAY,CAAC,IAAI,CAAC;wBAChB,KAAK,EAAE,SAAS;wBAChB,MAAM;wBACN,GAAG;wBACH,WAAW,EAAE,OAAO,CAAC,WAAW;qBACjC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,OAAO;YACP,WAAW;YACX,YAAY;YACZ,YAAY;SACb,CAAC;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,kBAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport { singular } from \"pluralize\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n /**\n * When using swagger with strict set to false and needs fallback to prisma for the required json schemas that where not manually provided through zod schemas or class validator classes.\n */\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) continue;\n\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await PrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n if (key.includes(\"ModelSchema\")) mappedKey = key;\n else mappedKey = `${key}ModelSchema`;\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAoBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,
|
|
1
|
+
{"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAoBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,oCAkCC;AAED,wDA2BC;AAUD,4DAWC;AAzJD,qDAAkE;AAElE,iFAA0E;AAC1E,kHAAsF;AACtF,mHAAwF;AACxF,0HAAmH;AACnH,wGAAkG;AAClG,4IAAoI;AACpI,iKAAmI;AACnI,kEAA0C;AAC1C,yGAA+E;AAC/E,qEAG0C;AAKnC,KAAK,UAAU,iCAAiC,CACrD,WAAwB;IAExB,QAAQ,WAAW,EAAE,OAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,KAAK,QAAQ;YACX,OAAO,MAAM,IAAA,wDAAyB,EAAC,WAAW,CAAC,CAAC;QACtD,KAAK,iBAAiB;YACpB,OAAO,MAAM,IAAA,yEAAiC,GAAE,CAAC;QACnD,KAAK,KAAK;YACR,OAAO,MAAM,IAAA,mCAAsB,GAAE,CAAC;QAC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AC;AACf,CAAC;AAUM,KAAK,UAAU,wBAAwB,CAC5C,MAAgC,EAChC,SAAiB,EACjB,WAAwB;IAExB,IAAI,WAAW,EAAE,OAAO,EAAE,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC1D,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,SAAS,CAAQ,CAAC;IAE/D,OAAO,CAAC,CAAC,gBAAgB,EAAE,CACzB,WAAW,CAAC,UAAU,EAAE,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAChE,EAAE,CAAC,IAAA,iBAAS,EAAC,MAAM,CAAC,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../../../exports\";\nimport { camelCase, pascalCase } from \"../../../../exports/utils\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { getSystemJsonSchemaPaths } from \"./get-system-json-schema-paths\";\nimport getAuthenticationJsonSchemaPaths from \"./get-authentication-json-schema-paths\";\nimport generateZodJsonSchemas from \"./json-schema-generators/generate-zod-json-schemas\";\nimport { generateClassValidatorJsonSchemas } from \"./json-schema-generators/generate-class-validator-json-schemas\";\nimport { generatePrismaJsonSchemas } from \"./json-schema-generators/generate-prisma-json-schemas\";\nimport { generatePrismaModelMainRoutesPaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths\";\nimport generatePrismaModelParentRoutePaths from \"./json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths\";\nimport sheu from \"../../../../utils/sheu\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport {\n getModuleComponents,\n ValidationFileMappingKey,\n} from \"../../../../utils/dynamic-loader\";\n\n/**\n * Helps choosing the right json schemas according to swagger configurations\n */\nexport async function getOpenAPIJsonSchemasByConfigMode(\n arkosConfig: ArkosConfig\n) {\n switch (arkosConfig?.swagger!.mode) {\n case \"prisma\":\n return await generatePrismaJsonSchemas(arkosConfig);\n case \"class-validator\":\n return await generateClassValidatorJsonSchemas();\n case \"zod\":\n return await generateZodJsonSchemas();\n default:\n throw Error(\n \"Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas\"\n );\n }\n}\n\nexport function getCorrectJsonSchemaName(\n type: string,\n modelName: string,\n suffix: \"Dto\" | \"Schema\"\n): string {\n const pascalModelName = pascalCase(modelName);\n\n const map: Record<string, string> = {\n model: pascalModelName,\n create: `Create${pascalModelName}`,\n createMany: `CreateMany${pascalModelName}`,\n findOne: `FindOne${pascalModelName}`,\n findMany: `FindMany${pascalModelName}`,\n update: `Update${pascalModelName}`,\n updateMany: `UpdateMany${pascalModelName}`,\n query: `Query${pascalModelName}`,\n login: \"Login\",\n signup: \"Signup\",\n updateMe: \"UpdateMe\",\n updatePassword: \"UpdatePassword\",\n };\n\n const baseName = map[type] ?? pascalCase(type);\n return `${baseName}${suffix}`;\n}\n\nexport function kebabToHuman(kebabStr: string): string {\n return kebabStr\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nexport function getSchemaRef(\n schemaName: string,\n mode: \"prisma\" | \"zod\" | \"class-validator\"\n): string {\n schemaName = pascalCase(schemaName);\n const specialCases = [\n \"getme\",\n \"updateme\",\n \"login\",\n \"signup\",\n \"updatepassword\",\n \"password\",\n \"me\",\n ];\n const isSpecialCase = specialCases.some(\n (keyword) => keyword === schemaName.toLowerCase()\n );\n\n if (isSpecialCase && mode === \"prisma\")\n return `#/components/schemas/${schemaName}Schema`;\n\n switch (mode) {\n case \"prisma\":\n return `#/components/schemas/${schemaName}ModelSchema`;\n case \"zod\":\n return `#/components/schemas/${schemaName}Schema`;\n case \"class-validator\":\n return `#/components/schemas/${schemaName}Dto`;\n default:\n sheu.error(\n `Unknown Arkos.js swagger documentation provided, available options are prisma, zod or class-validator but received ${mode}`\n );\n return \"\";\n }\n}\n\nexport async function generatePathsForModels(\n arkosConfig: ArkosConfig\n): Promise<OpenAPIV3.PathsObject> {\n const swaggerConfig = arkosConfig?.swagger;\n\n if (!swaggerConfig) return {};\n\n let paths: OpenAPIV3.PathsObject = {};\n const models = prismaSchemaParser.getModelsAsArrayOfStrings();\n\n for (const model of models) {\n await generatePrismaModelMainRoutesPaths(model, paths, arkosConfig);\n\n await generatePrismaModelParentRoutePaths(model, paths, arkosConfig);\n }\n\n paths = {\n ...paths,\n ...getSystemJsonSchemaPaths(),\n };\n\n paths = {\n ...paths,\n ...((await getAuthenticationJsonSchemaPaths(arkosConfig)) || {}),\n };\n\n return paths;\n}\n\n/**\n * Helps in finding out whether a given dto/schema file exits under the user project according to the validation arkos configuration.\n *\n * @param action {ValidationFileMappingKey} - the action of the dto, e.g: create, findMany.\n * @param modelName {string} - the model to be checked\n * @param arkosConfig {ArkosConfig} - the arkos.js configuration\n * @returns boolean\n */\nexport async function localValidatorFileExists(\n action: ValidationFileMappingKey,\n modelName: string,\n arkosConfig: ArkosConfig\n) {\n if (arkosConfig?.swagger?.mode === \"prisma\") return false;\n const moduleComponents = getModuleComponents(modelName) as any;\n\n return !!moduleComponents?.[\n arkosConfig.validation?.resolver === \"zod\" ? \"schemas\" : \"dtos\"\n ]?.[camelCase(action)];\n}\n"]}
|
|
@@ -16,8 +16,9 @@ const BUILD_DIR = ".build";
|
|
|
16
16
|
const MODULE_TYPES = ["cjs", "esm"];
|
|
17
17
|
function buildCommand(options = {}) {
|
|
18
18
|
const fileExt = (0, fs_helpers_1.getUserFileExtension)();
|
|
19
|
-
process.env.NODE_ENV
|
|
20
|
-
|
|
19
|
+
if (process.env.NODE_ENV === "test" || !process.env.NODE_ENV)
|
|
20
|
+
process.env.NODE_ENV = "production";
|
|
21
|
+
process.env.ARKOS_BUILD = "true";
|
|
21
22
|
const envFiles = (0, dotenv_helpers_1.loadEnvironmentVariables)();
|
|
22
23
|
const moduleType = validateModuleType(options.module);
|
|
23
24
|
try {
|