arkos 2.0.0-next.10 → 2.0.0-next.12
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.service.js +2 -2
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/model-openapi-generator.js +61 -87
- package/dist/cjs/modules/base/utils/model-openapi-generator.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +1 -0
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +2 -2
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +122 -0
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +2 -2
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/base/utils/model-openapi-generator.js +61 -87
- package/dist/esm/modules/base/utils/model-openapi-generator.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +1 -0
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +2 -2
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +122 -0
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/types/modules/auth/auth.service.d.ts +1 -1
- package/dist/types/utils/prisma/prisma-json-schema-generator.d.ts +7 -0
- package/package.json +1 -1
|
@@ -189,7 +189,7 @@ class AuthService {
|
|
|
189
189
|
}
|
|
190
190
|
userChangedPasswordAfter(user, JWTTimestamp) {
|
|
191
191
|
if (user.passwordChangedAt) {
|
|
192
|
-
const convertedTimestamp = parseInt(String(user.passwordChangedAt.getTime() / 1000), 10);
|
|
192
|
+
const convertedTimestamp = parseInt(String(new Date(user.passwordChangedAt).getTime() / 1000), 10);
|
|
193
193
|
return JWTTimestamp < convertedTimestamp;
|
|
194
194
|
}
|
|
195
195
|
return false;
|
|
@@ -329,7 +329,7 @@ class AuthService {
|
|
|
329
329
|
req.accessToken = token;
|
|
330
330
|
return user;
|
|
331
331
|
}
|
|
332
|
-
authorize(
|
|
332
|
+
authorize(action, resource, rule) {
|
|
333
333
|
auth_action_service_1.default.add(action, resource, { [action]: rule });
|
|
334
334
|
return (0, catch_async_1.default)(async (req, _, next) => {
|
|
335
335
|
const hooks = (0, server_1.getArkosConfig)()?.authentication?.hooks?.authorize;
|
|
@@ -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;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAUlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAqmBrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,CAAC;YAEpE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;YACvD,IAAI,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO;gBACnC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YAEpD,IAAI,CAAC,MAAM,CAAC,OA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,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,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;AAj0BD,kCAi0BC;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 AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthAfterHookHandler,\n AuthErrorHookHandler,\n AuthHookHandler,\n} from \"../../types/arkos-config/utils\";\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 * Runs a chain of `before` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run, core logic is skipped.\n * - If a hook calls `ctx.skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runHooks(\n hooks: AuthHookHandler | AuthHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req` and `next` only — no `skip` since\n * there is nothing meaningful to skip to after the pipeline has completed.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, error? }`\n */\n private async runAfterHooks(\n hooks: AuthAfterHookHandler | AuthAfterHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n });\n\n if (hookErr) return { stopped: true, error: hookErr };\n if (nextCalled) return { stopped: true };\n }\n\n return { stopped: false };\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `error`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards the error (original or replaced) to the global error handler.\n * - If a hook calls `ctx.skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runErrorHooks(\n hooks: AuthErrorHookHandler | AuthErrorHookHandler[] | undefined,\n error: unknown,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n error,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\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 if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\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 private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\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 = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\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 * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\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 \"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 if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\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 req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\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 \"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 \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n resource: string,\n action: AccessAction,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\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 if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\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 * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\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: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\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 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;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAUlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,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J,6BAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC;QAEvD,OAAO,KAAK,EAAE,IAAsB,EAAoB,EAAE;YAExD,MAAM,OAAO,GAAG,IAAA,uBAAc,GAAE,CAAC;YAEjC,IAAI,CAAC,IAAA,4CAAqB,GAAE;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAA,8CAAuB,GAAE;gBAAE,OAAO,KAAK,CAAC;YAC7C,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,EAAE,WAAW;gBAAE,OAAO,IAAI,CAAC;YAEnC,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,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;AAj0BD,kCAi0BC;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 AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthAfterHookHandler,\n AuthErrorHookHandler,\n AuthHookHandler,\n} from \"../../types/arkos-config/utils\";\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 * Runs a chain of `before` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run, core logic is skipped.\n * - If a hook calls `ctx.skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runHooks(\n hooks: AuthHookHandler | AuthHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req` and `next` only — no `skip` since\n * there is nothing meaningful to skip to after the pipeline has completed.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, error? }`\n */\n private async runAfterHooks(\n hooks: AuthAfterHookHandler | AuthAfterHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n });\n\n if (hookErr) return { stopped: true, error: hookErr };\n if (nextCalled) return { stopped: true };\n }\n\n return { stopped: false };\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `error`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards the error (original or replaced) to the global error handler.\n * - If a hook calls `ctx.skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runErrorHooks(\n hooks: AuthErrorHookHandler | AuthErrorHookHandler[] | undefined,\n error: unknown,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n error,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\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 if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\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(new Date(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 private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\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 = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\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 * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\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 \"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 if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\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 req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\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 \"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 \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\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 if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\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 * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\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: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\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 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"]}
|
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
const prisma_1 = require("../../../exports/prisma/index.js");
|
|
7
7
|
const utils_1 = require("../../../exports/utils/index.js");
|
|
8
8
|
const arkos_config_helpers_1 = require("../../../utils/helpers/arkos-config.helpers.js");
|
|
9
|
+
const text_helpers_1 = require("../../../utils/helpers/text.helpers.js");
|
|
9
10
|
const prisma_json_schema_generator_1 = __importDefault(require("../../../utils/prisma/prisma-json-schema-generator.js"));
|
|
10
11
|
const pluralize_1 = __importDefault(require("pluralize"));
|
|
11
12
|
class ModelOpenAPIGenerator {
|
|
@@ -48,6 +49,10 @@ class ModelOpenAPIGenerator {
|
|
|
48
49
|
const existingOpenApi = endpointRouterConfig?.experimental?.openapi || {};
|
|
49
50
|
const hasBodyValidation = typeof endpointRouterConfig?.validation !== "boolean" &&
|
|
50
51
|
!!endpointRouterConfig?.validation?.body;
|
|
52
|
+
const hasQueryValidation = typeof endpointRouterConfig?.validation !== "boolean" &&
|
|
53
|
+
!!endpointRouterConfig?.validation?.query;
|
|
54
|
+
const hasParamsValidation = typeof endpointRouterConfig?.validation !== "boolean" &&
|
|
55
|
+
!!endpointRouterConfig?.validation?.params;
|
|
51
56
|
const model = this.getModel(modelNameInKebab);
|
|
52
57
|
const pascalModelName = (0, utils_1.pascalCase)(modelNameInKebab);
|
|
53
58
|
const humanReadableName = modelNameInKebab.replaceAll("-", " ");
|
|
@@ -58,7 +63,7 @@ class ModelOpenAPIGenerator {
|
|
|
58
63
|
return {
|
|
59
64
|
...existingOpenApi,
|
|
60
65
|
tags: [
|
|
61
|
-
(0,
|
|
66
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
62
67
|
...(existingOpenApi?.tags || []),
|
|
63
68
|
].filter((tag) => tag !== "Defaults"),
|
|
64
69
|
summary: existingOpenApi?.summary || `Create a new ${humanReadableName}`,
|
|
@@ -97,7 +102,7 @@ class ModelOpenAPIGenerator {
|
|
|
97
102
|
return {
|
|
98
103
|
...existingOpenApi,
|
|
99
104
|
tags: [
|
|
100
|
-
(0,
|
|
105
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
101
106
|
...(existingOpenApi?.tags || []),
|
|
102
107
|
].filter((tag) => tag !== "Defaults"),
|
|
103
108
|
summary: existingOpenApi?.summary || `Get ${humanReadableNamePlural}`,
|
|
@@ -108,38 +113,9 @@ class ModelOpenAPIGenerator {
|
|
|
108
113
|
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
109
114
|
parameters: [
|
|
110
115
|
...(existingOpenApi?.parameters || []),
|
|
111
|
-
...
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
in: "query",
|
|
115
|
-
description: "Filter criteria in JSON format",
|
|
116
|
-
schema: { type: "string" },
|
|
117
|
-
},
|
|
118
|
-
{
|
|
119
|
-
name: "sort",
|
|
120
|
-
in: "query",
|
|
121
|
-
description: "Sort field (prefix with '-' for descending order)",
|
|
122
|
-
schema: { type: "string" },
|
|
123
|
-
},
|
|
124
|
-
{
|
|
125
|
-
name: "page",
|
|
126
|
-
in: "query",
|
|
127
|
-
description: "Page number (starts from 1)",
|
|
128
|
-
schema: { type: "integer", minimum: 1 },
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
name: "limit",
|
|
132
|
-
in: "query",
|
|
133
|
-
description: "Number of items per page",
|
|
134
|
-
schema: { type: "integer", minimum: 1, maximum: 100 },
|
|
135
|
-
},
|
|
136
|
-
{
|
|
137
|
-
name: "fields",
|
|
138
|
-
in: "query",
|
|
139
|
-
description: "Comma-separated list of fields to include in response",
|
|
140
|
-
schema: { type: "string" },
|
|
141
|
-
},
|
|
142
|
-
].filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
116
|
+
...(!hasQueryValidation
|
|
117
|
+
? prisma_json_schema_generator_1.default.generateQueryFilterParameters(model)
|
|
118
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
143
119
|
],
|
|
144
120
|
responses: {
|
|
145
121
|
...(existingOpenApi?.responses || {}),
|
|
@@ -174,7 +150,7 @@ class ModelOpenAPIGenerator {
|
|
|
174
150
|
return {
|
|
175
151
|
...existingOpenApi,
|
|
176
152
|
tags: [
|
|
177
|
-
(0,
|
|
153
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
178
154
|
...(existingOpenApi?.tags || []),
|
|
179
155
|
].filter((tag) => tag !== "Defaults"),
|
|
180
156
|
summary: existingOpenApi?.summary ||
|
|
@@ -225,7 +201,7 @@ class ModelOpenAPIGenerator {
|
|
|
225
201
|
return {
|
|
226
202
|
...existingOpenApi,
|
|
227
203
|
tags: [
|
|
228
|
-
(0,
|
|
204
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
229
205
|
...(existingOpenApi?.tags || []),
|
|
230
206
|
].filter((tag) => tag !== "Defaults"),
|
|
231
207
|
summary: existingOpenApi?.summary ||
|
|
@@ -233,19 +209,15 @@ class ModelOpenAPIGenerator {
|
|
|
233
209
|
description: existingOpenApi?.description ||
|
|
234
210
|
`Updates multiple ${humanReadableNamePlural} records that match the specified filter criteria`,
|
|
235
211
|
operationId: existingOpenApi?.operationId || `updateMany${pascalModelName}`,
|
|
236
|
-
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
237
212
|
parameters: [
|
|
238
213
|
...(existingOpenApi?.parameters || []),
|
|
239
|
-
...
|
|
240
|
-
{
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
required: true,
|
|
245
|
-
schema: { type: "string" },
|
|
246
|
-
},
|
|
247
|
-
].filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
214
|
+
...(!hasQueryValidation
|
|
215
|
+
? prisma_json_schema_generator_1.default.generateQueryFilterParameters(model, {
|
|
216
|
+
modelFieldsOnly: true,
|
|
217
|
+
})
|
|
218
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
248
219
|
],
|
|
220
|
+
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
249
221
|
...(!hasBodyValidation && {
|
|
250
222
|
requestBody: existingOpenApi?.requestBody || {
|
|
251
223
|
description: `Partial ${humanReadableName} data to update`,
|
|
@@ -285,7 +257,7 @@ class ModelOpenAPIGenerator {
|
|
|
285
257
|
return {
|
|
286
258
|
...existingOpenApi,
|
|
287
259
|
tags: [
|
|
288
|
-
(0,
|
|
260
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
289
261
|
...(existingOpenApi?.tags || []),
|
|
290
262
|
].filter((tag) => tag !== "Defaults"),
|
|
291
263
|
summary: existingOpenApi?.summary ||
|
|
@@ -293,19 +265,15 @@ class ModelOpenAPIGenerator {
|
|
|
293
265
|
description: existingOpenApi?.description ||
|
|
294
266
|
`Deletes multiple ${humanReadableNamePlural} records that match the specified filter criteria`,
|
|
295
267
|
operationId: existingOpenApi?.operationId || `deleteMany${pascalModelName}`,
|
|
296
|
-
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
297
268
|
parameters: [
|
|
298
269
|
...(existingOpenApi?.parameters || []),
|
|
299
|
-
...
|
|
300
|
-
{
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
required: true,
|
|
305
|
-
schema: { type: "string" },
|
|
306
|
-
},
|
|
307
|
-
].filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
270
|
+
...(!hasQueryValidation
|
|
271
|
+
? prisma_json_schema_generator_1.default.generateQueryFilterParameters(model, {
|
|
272
|
+
modelFieldsOnly: true,
|
|
273
|
+
})
|
|
274
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
308
275
|
],
|
|
276
|
+
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
309
277
|
responses: {
|
|
310
278
|
...(existingOpenApi?.responses || {}),
|
|
311
279
|
"200": existingOpenApi?.responses?.["200"] || {
|
|
@@ -334,7 +302,7 @@ class ModelOpenAPIGenerator {
|
|
|
334
302
|
return {
|
|
335
303
|
...existingOpenApi,
|
|
336
304
|
tags: [
|
|
337
|
-
(0,
|
|
305
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
338
306
|
...(existingOpenApi?.tags || []),
|
|
339
307
|
].filter((tag) => tag !== "Defaults"),
|
|
340
308
|
summary: existingOpenApi?.summary || `Get ${humanReadableName} by ID`,
|
|
@@ -344,15 +312,17 @@ class ModelOpenAPIGenerator {
|
|
|
344
312
|
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
345
313
|
parameters: [
|
|
346
314
|
...(existingOpenApi?.parameters || []),
|
|
347
|
-
...
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
315
|
+
...(!hasParamsValidation
|
|
316
|
+
? [
|
|
317
|
+
{
|
|
318
|
+
name: "id",
|
|
319
|
+
in: "path",
|
|
320
|
+
description: `Unique identifier of the ${humanReadableName}`,
|
|
321
|
+
required: true,
|
|
322
|
+
schema: { type: "string" },
|
|
323
|
+
},
|
|
324
|
+
]
|
|
325
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
356
326
|
],
|
|
357
327
|
responses: {
|
|
358
328
|
...(existingOpenApi?.responses || {}),
|
|
@@ -374,7 +344,7 @@ class ModelOpenAPIGenerator {
|
|
|
374
344
|
return {
|
|
375
345
|
...existingOpenApi,
|
|
376
346
|
tags: [
|
|
377
|
-
(0,
|
|
347
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
378
348
|
...(existingOpenApi?.tags || []),
|
|
379
349
|
].filter((tag) => tag !== "Defaults"),
|
|
380
350
|
summary: existingOpenApi?.summary || `Update ${humanReadableName} by ID`,
|
|
@@ -384,15 +354,17 @@ class ModelOpenAPIGenerator {
|
|
|
384
354
|
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
385
355
|
parameters: [
|
|
386
356
|
...(existingOpenApi?.parameters || []),
|
|
387
|
-
...
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
357
|
+
...(!hasParamsValidation
|
|
358
|
+
? [
|
|
359
|
+
{
|
|
360
|
+
name: "id",
|
|
361
|
+
in: "path",
|
|
362
|
+
description: `Unique identifier of the ${humanReadableName}`,
|
|
363
|
+
required: true,
|
|
364
|
+
schema: { type: "string" },
|
|
365
|
+
},
|
|
366
|
+
]
|
|
367
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
396
368
|
],
|
|
397
369
|
...(!hasBodyValidation && {
|
|
398
370
|
requestBody: existingOpenApi?.requestBody || {
|
|
@@ -428,7 +400,7 @@ class ModelOpenAPIGenerator {
|
|
|
428
400
|
return {
|
|
429
401
|
...existingOpenApi,
|
|
430
402
|
tags: [
|
|
431
|
-
(0,
|
|
403
|
+
(0, text_helpers_1.capitalize)(humanReadableNamePlural),
|
|
432
404
|
...(existingOpenApi?.tags || []),
|
|
433
405
|
].filter((tag) => tag !== "Defaults"),
|
|
434
406
|
summary: existingOpenApi?.summary || `Delete ${humanReadableName} by ID`,
|
|
@@ -438,15 +410,17 @@ class ModelOpenAPIGenerator {
|
|
|
438
410
|
security: existingOpenApi?.security || [{ BearerAuth: [] }],
|
|
439
411
|
parameters: [
|
|
440
412
|
...(existingOpenApi?.parameters || []),
|
|
441
|
-
...
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
413
|
+
...(!hasParamsValidation
|
|
414
|
+
? [
|
|
415
|
+
{
|
|
416
|
+
name: "id",
|
|
417
|
+
in: "path",
|
|
418
|
+
description: `Unique identifier of the ${humanReadableName}`,
|
|
419
|
+
required: true,
|
|
420
|
+
schema: { type: "string" },
|
|
421
|
+
},
|
|
422
|
+
]
|
|
423
|
+
: []).filter((p) => !(existingOpenApi?.parameters || []).find((ep) => ep.name === p.name && ep.in === p.in)),
|
|
450
424
|
],
|
|
451
425
|
responses: {
|
|
452
426
|
...(existingOpenApi?.responses || {}),
|