payload 3.66.0 → 3.67.0-internal.1ea538b
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/auth/operations/forgotPassword.d.ts.map +1 -1
- package/dist/auth/operations/forgotPassword.js +7 -12
- package/dist/auth/operations/forgotPassword.js.map +1 -1
- package/dist/auth/operations/login.d.ts.map +1 -1
- package/dist/auth/operations/login.js +7 -12
- package/dist/auth/operations/login.js.map +1 -1
- package/dist/auth/operations/refresh.d.ts.map +1 -1
- package/dist/auth/operations/refresh.js +7 -12
- package/dist/auth/operations/refresh.js.map +1 -1
- package/dist/auth/operations/resetPassword.d.ts.map +1 -1
- package/dist/auth/operations/resetPassword.js +7 -12
- package/dist/auth/operations/resetPassword.js.map +1 -1
- package/dist/auth/operations/unlock.d.ts.map +1 -1
- package/dist/auth/operations/unlock.js +14 -1
- package/dist/auth/operations/unlock.js.map +1 -1
- package/dist/collections/config/sanitize.d.ts.map +1 -1
- package/dist/collections/config/sanitize.js +2 -0
- package/dist/collections/config/sanitize.js.map +1 -1
- package/dist/collections/config/types.d.ts +7 -19
- package/dist/collections/config/types.d.ts.map +1 -1
- package/dist/collections/config/types.js.map +1 -1
- package/dist/collections/operations/count.d.ts.map +1 -1
- package/dist/collections/operations/count.js +7 -12
- package/dist/collections/operations/count.js.map +1 -1
- package/dist/collections/operations/countVersions.d.ts.map +1 -1
- package/dist/collections/operations/countVersions.js +7 -12
- package/dist/collections/operations/countVersions.js.map +1 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +10 -14
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/delete.d.ts.map +1 -1
- package/dist/collections/operations/delete.js +9 -13
- package/dist/collections/operations/delete.js.map +1 -1
- package/dist/collections/operations/deleteByID.d.ts.map +1 -1
- package/dist/collections/operations/deleteByID.js +9 -13
- package/dist/collections/operations/deleteByID.js.map +1 -1
- package/dist/collections/operations/find.d.ts.map +1 -1
- package/dist/collections/operations/find.js +9 -13
- package/dist/collections/operations/find.js.map +1 -1
- package/dist/collections/operations/findByID.d.ts.map +1 -1
- package/dist/collections/operations/findByID.js +22 -26
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/collections/operations/findDistinct.d.ts.map +1 -1
- package/dist/collections/operations/findDistinct.js +7 -12
- package/dist/collections/operations/findDistinct.js.map +1 -1
- package/dist/collections/operations/findVersionByID.d.ts.map +1 -1
- package/dist/collections/operations/findVersionByID.js +20 -1
- package/dist/collections/operations/findVersionByID.js.map +1 -1
- package/dist/collections/operations/findVersions.d.ts.map +1 -1
- package/dist/collections/operations/findVersions.js +24 -5
- package/dist/collections/operations/findVersions.js.map +1 -1
- package/dist/collections/operations/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/restoreVersion.js +9 -13
- package/dist/collections/operations/restoreVersion.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +9 -13
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.d.ts.map +1 -1
- package/dist/collections/operations/updateByID.js +7 -12
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/collections/operations/utilities/buildAfterOperation.d.ts +6 -0
- package/dist/collections/operations/utilities/buildAfterOperation.d.ts.map +1 -0
- package/dist/collections/operations/{utils.js → utilities/buildAfterOperation.js} +1 -1
- package/dist/collections/operations/utilities/buildAfterOperation.js.map +1 -0
- package/dist/collections/operations/utilities/buildBeforeOperation.d.ts +47 -0
- package/dist/collections/operations/utilities/buildBeforeOperation.d.ts.map +1 -0
- package/dist/collections/operations/utilities/buildBeforeOperation.js +25 -0
- package/dist/collections/operations/utilities/buildBeforeOperation.js.map +1 -0
- package/dist/collections/operations/utilities/types.d.ts +216 -0
- package/dist/collections/operations/utilities/types.d.ts.map +1 -0
- package/dist/collections/operations/utilities/types.js +23 -0
- package/dist/collections/operations/utilities/types.js.map +1 -0
- package/dist/collections/operations/utilities/update.d.ts.map +1 -1
- package/dist/collections/operations/utilities/update.js +4 -2
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/config/sanitize.d.ts.map +1 -1
- package/dist/config/sanitize.js +2 -2
- package/dist/config/sanitize.js.map +1 -1
- package/dist/exports/shared.d.ts +1 -0
- package/dist/exports/shared.d.ts.map +1 -1
- package/dist/exports/shared.js +1 -0
- package/dist/exports/shared.js.map +1 -1
- package/dist/fields/baseFields/slug/generateSlug.d.ts.map +1 -1
- package/dist/fields/baseFields/slug/generateSlug.js +2 -2
- package/dist/fields/baseFields/slug/generateSlug.js.map +1 -1
- package/dist/fields/config/types.d.ts +2 -0
- package/dist/fields/config/types.d.ts.map +1 -1
- package/dist/fields/config/types.js.map +1 -1
- package/dist/globals/config/types.d.ts +1 -1
- package/dist/globals/config/types.d.ts.map +1 -1
- package/dist/globals/config/types.js.map +1 -1
- package/dist/globals/operations/findOne.d.ts.map +1 -1
- package/dist/globals/operations/findOne.js +4 -3
- package/dist/globals/operations/findOne.js.map +1 -1
- package/dist/globals/operations/update.d.ts.map +1 -1
- package/dist/globals/operations/update.js +3 -2
- package/dist/globals/operations/update.js.map +1 -1
- package/dist/index.bundled.d.ts +200 -119
- package/dist/utilities/getVersionsConfig.d.ts +37 -0
- package/dist/utilities/getVersionsConfig.d.ts.map +1 -0
- package/dist/utilities/getVersionsConfig.js +44 -0
- package/dist/utilities/getVersionsConfig.js.map +1 -0
- package/dist/versions/buildCollectionFields.d.ts.map +1 -1
- package/dist/versions/buildCollectionFields.js +3 -2
- package/dist/versions/buildCollectionFields.js.map +1 -1
- package/dist/versions/buildGlobalFields.d.ts.map +1 -1
- package/dist/versions/buildGlobalFields.js +3 -2
- package/dist/versions/buildGlobalFields.js.map +1 -1
- package/dist/versions/getLatestCollectionVersion.d.ts.map +1 -1
- package/dist/versions/getLatestCollectionVersion.js +3 -1
- package/dist/versions/getLatestCollectionVersion.js.map +1 -1
- package/dist/versions/getLatestGlobalVersion.d.ts.map +1 -1
- package/dist/versions/getLatestGlobalVersion.js +3 -2
- package/dist/versions/getLatestGlobalVersion.js.map +1 -1
- package/dist/versions/saveVersion.d.ts.map +1 -1
- package/dist/versions/saveVersion.js +2 -1
- package/dist/versions/saveVersion.js.map +1 -1
- package/package.json +2 -2
- package/dist/collections/operations/utils.d.ts +0 -105
- package/dist/collections/operations/utils.d.ts.map +0 -1
- package/dist/collections/operations/utils.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forgotPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/forgotPassword.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACX,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"forgotPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/forgotPassword.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACX,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AAajE,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,cAAc,IAAI;IACpD,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE;QACJ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KACvB,GAAG,gCAAgC,CAAC,KAAK,CAAC,CAAC,gBAAgB,CAAC,CAAA;IAC7D,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,MAAM,MAAM,MAAM,GAAG,MAAM,CAAA;AAE3B,eAAO,MAAM,uBAAuB,GAAU,KAAK,SAAS,cAAc,gBAC1D,SAAS,CAAC,KAAK,CAAC,KAC7B,OAAO,CAAC,IAAI,GAAG,MAAM,CA6LvB,CAAA"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { status as httpStatus } from 'http-status';
|
|
3
3
|
import { URL } from 'url';
|
|
4
|
-
import { buildAfterOperation } from '../../collections/operations/
|
|
4
|
+
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
|
|
5
|
+
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
|
|
5
6
|
import { APIError } from '../../errors/index.js';
|
|
6
7
|
import { Forbidden } from '../../index.js';
|
|
7
8
|
import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
|
|
@@ -28,17 +29,11 @@ export const forgotPasswordOperation = async (incomingArgs)=>{
|
|
|
28
29
|
// /////////////////////////////////////
|
|
29
30
|
// beforeOperation - Collection
|
|
30
31
|
// /////////////////////////////////////
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
context: args.req.context,
|
|
37
|
-
operation: 'forgotPassword',
|
|
38
|
-
req: args.req
|
|
39
|
-
}) || args;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
32
|
+
args = await buildBeforeOperation({
|
|
33
|
+
args,
|
|
34
|
+
collection: args.collection.config,
|
|
35
|
+
operation: 'forgotPassword'
|
|
36
|
+
});
|
|
42
37
|
const { collection: { config: collectionConfig }, disableEmail, expiration, req: { payload: { config, email }, payload }, req } = args;
|
|
43
38
|
// /////////////////////////////////////
|
|
44
39
|
// Forget password
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/forgotPassword.ts"],"sourcesContent":["import crypto from 'crypto'\nimport { status as httpStatus } from 'http-status'\nimport { URL } from 'url'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { APIError } from '../../errors/index.js'\nimport { Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { formatAdminURL } from '../../utilities/formatAdminURL.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: {\n [key: string]: unknown\n } & AuthOperationsFromCollectionSlug<TSlug>['forgotPassword']\n disableEmail?: boolean\n expiration?: number\n req: PayloadRequest\n}\n\nexport type Result = string\n\nexport const forgotPasswordOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<null | string> => {\n const loginWithUsername = incomingArgs.collection.config.auth.loginWithUsername\n const { data } = incomingArgs\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n const sanitizedEmail =\n (canLoginWithEmail && (incomingArgs.data.email || '').toLowerCase().trim()) || null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n let args = incomingArgs\n\n if (incomingArgs.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(incomingArgs.req.t)\n }\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n if (args.collection.config.hooks?.beforeOperation?.length) {\n for (const hook of args.collection.config.hooks.beforeOperation) {\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'forgotPassword',\n req: args.req,\n })) || args\n }\n }\n\n const {\n collection: { config: collectionConfig },\n disableEmail,\n expiration,\n req: {\n payload: { config, email },\n payload,\n },\n req,\n } = args\n\n // /////////////////////////////////////\n // Forget password\n // /////////////////////////////////////\n\n let token: string = crypto.randomBytes(20).toString('hex')\n type UserDoc = {\n email?: string\n id: number | string\n resetPasswordExpiration?: string\n resetPasswordToken?: string\n }\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let whereConstraint: Where = {}\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = {\n email: {\n equals: sanitizedEmail,\n },\n }\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = {\n username: {\n equals: sanitizedUsername,\n },\n }\n }\n\n // Exclude trashed users unless `trash: true`\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = await payload.db.findOne<UserDoc>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n\n // We don't want to indicate specifically that an email was not found,\n // as doing so could lead to the exposure of registered emails.\n // Therefore, we prefer to fail silently.\n if (!user) {\n await commitTransaction(args.req)\n return null\n }\n\n const resetPasswordExpiration = new Date(\n Date.now() + (collectionConfig.auth?.forgotPassword?.expiration ?? expiration ?? 3600000),\n ).toISOString()\n\n user = await payload.update({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n resetPasswordExpiration,\n resetPasswordToken: token,\n },\n req,\n })\n\n if (!disableEmail && user.email) {\n const protocol = new URL(req.url!).protocol // includes the final :\n const serverURL =\n config.serverURL !== null && config.serverURL !== ''\n ? config.serverURL\n : `${protocol}//${req.headers.get('host')}`\n const forgotURL = formatAdminURL({\n adminRoute: config.routes.admin,\n path: `${config.admin.routes.reset}/${token}`,\n serverURL,\n })\n let html = `${req.t('authentication:youAreReceivingResetPassword')}\n <a href=\"${forgotURL}\">${forgotURL}</a>\n ${req.t('authentication:youDidNotRequestPassword')}`\n\n if (typeof collectionConfig.auth.forgotPassword?.generateEmailHTML === 'function') {\n html = await collectionConfig.auth.forgotPassword.generateEmailHTML({\n req,\n token,\n user,\n })\n }\n\n let subject = req.t('authentication:resetYourPassword')\n\n if (typeof collectionConfig.auth.forgotPassword?.generateEmailSubject === 'function') {\n subject = await collectionConfig.auth.forgotPassword.generateEmailSubject({\n req,\n token,\n user,\n })\n }\n\n await email.sendEmail({\n from: `\"${email.defaultFromName}\" <${email.defaultFromAddress}>`,\n html,\n subject,\n to: user.email,\n })\n }\n\n // /////////////////////////////////////\n // afterForgotPassword - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterForgotPassword?.length) {\n for (const hook of collectionConfig.hooks.afterForgotPassword) {\n await hook({ args, collection: args.collection?.config, context: req.context })\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n token = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'forgotPassword',\n result: token,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return token\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["crypto","status","httpStatus","URL","buildAfterOperation","APIError","Forbidden","appendNonTrashedFilter","commitTransaction","formatAdminURL","initTransaction","killTransaction","getLoginOptions","forgotPasswordOperation","incomingArgs","loginWithUsername","collection","config","auth","data","canLoginWithEmail","canLoginWithUsername","sanitizedEmail","email","toLowerCase","trim","sanitizedUsername","username","args","disableLocalStrategy","req","t","BAD_REQUEST","shouldCommit","hooks","beforeOperation","length","hook","context","operation","collectionConfig","disableEmail","expiration","payload","token","randomBytes","toString","whereConstraint","equals","enableTrash","trash","where","user","db","findOne","slug","resetPasswordExpiration","Date","now","forgotPassword","toISOString","update","id","resetPasswordToken","protocol","url","serverURL","headers","get","forgotURL","adminRoute","routes","admin","path","reset","html","generateEmailHTML","subject","generateE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C,iBAAiBtB,IAAI,CAACyC,cAAc,CAACiB,iBAAiB,CAAC;oBAClE9C;oBACAc;oBACAQ;gBACF;YACF;YAEA,IAAIyB,UAAU/C,IAAIC,CAAC,CAAC;YAEpB,IAAI,OAAOS,iBAAiBtB,IAAI,CAACyC,cAAc,EAAEmB,yBAAyB,YAAY;gBACpFD,UAAU,MAAMrC,iBAAiBtB,IAAI,CAACyC,cAAc,CAACmB,oBAAoB,CAAC;oBACxEhD;oBACAc;oBACAQ;gBACF;YACF;YAEA,MAAM7B,MAAMwD,SAAS,CAAC;gBACpBC,MAAM,CAAC,CAAC,EAAEzD,MAAM0D,eAAe,CAAC,GAAG,EAAE1D,MAAM2D,kBAAkB,CAAC,CAAC,CAAC;gBAChEP;gBACAE;gBACAM,IAAI/B,KAAK7B,KAAK;YAChB;QACF;QAEA,wCAAwC;QACxC,mCAAmC;QACnC,wCAAwC;QAExC,IAAIiB,iBAAiBN,KAAK,EAAEkD,qBAAqBhD,QAAQ;YACvD,KAAK,MAAMC,QAAQG,iBAAiBN,KAAK,CAACkD,mBAAmB,CAAE;gBAC7D,MAAM/C,KAAK;oBAAET;oBAAMZ,YAAYY,KAAKZ,UAAU,EAAEC;oBAAQqB,SAASR,IAAIQ,OAAO;gBAAC;YAC/E;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCM,QAAQ,MAAMxC,oBAAoB;YAChCwB;YACAZ,YAAYY,KAAKZ,UAAU,EAAEC;YAC7BsB,WAAW;YACX8C,QAAQzC;QACV;QAEA,IAAIX,cAAc;YAChB,MAAMzB,kBAAkBsB;QAC1B;QAEA,OAAOc;IACT,EAAE,OAAO0C,OAAgB;QACvB,MAAM3E,gBAAgBiB,KAAKE,GAAG;QAC9B,MAAMwD;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/forgotPassword.ts"],"sourcesContent":["import crypto from 'crypto'\nimport { status as httpStatus } from 'http-status'\nimport { URL } from 'url'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError } from '../../errors/index.js'\nimport { Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { formatAdminURL } from '../../utilities/formatAdminURL.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: {\n [key: string]: unknown\n } & AuthOperationsFromCollectionSlug<TSlug>['forgotPassword']\n disableEmail?: boolean\n expiration?: number\n req: PayloadRequest\n}\n\nexport type Result = string\n\nexport const forgotPasswordOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<null | string> => {\n const loginWithUsername = incomingArgs.collection.config.auth.loginWithUsername\n const { data } = incomingArgs\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n const sanitizedEmail =\n (canLoginWithEmail && (incomingArgs.data.email || '').toLowerCase().trim()) || null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n let args = incomingArgs\n\n if (incomingArgs.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(incomingArgs.req.t)\n }\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'forgotPassword',\n })\n\n const {\n collection: { config: collectionConfig },\n disableEmail,\n expiration,\n req: {\n payload: { config, email },\n payload,\n },\n req,\n } = args\n\n // /////////////////////////////////////\n // Forget password\n // /////////////////////////////////////\n\n let token: string = crypto.randomBytes(20).toString('hex')\n type UserDoc = {\n email?: string\n id: number | string\n resetPasswordExpiration?: string\n resetPasswordToken?: string\n }\n\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n let whereConstraint: Where = {}\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = {\n email: {\n equals: sanitizedEmail,\n },\n }\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = {\n username: {\n equals: sanitizedUsername,\n },\n }\n }\n\n // Exclude trashed users unless `trash: true`\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = await payload.db.findOne<UserDoc>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })\n\n // We don't want to indicate specifically that an email was not found,\n // as doing so could lead to the exposure of registered emails.\n // Therefore, we prefer to fail silently.\n if (!user) {\n await commitTransaction(args.req)\n return null\n }\n\n const resetPasswordExpiration = new Date(\n Date.now() + (collectionConfig.auth?.forgotPassword?.expiration ?? expiration ?? 3600000),\n ).toISOString()\n\n user = await payload.update({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n resetPasswordExpiration,\n resetPasswordToken: token,\n },\n req,\n })\n\n if (!disableEmail && user.email) {\n const protocol = new URL(req.url!).protocol // includes the final :\n const serverURL =\n config.serverURL !== null && config.serverURL !== ''\n ? config.serverURL\n : `${protocol}//${req.headers.get('host')}`\n const forgotURL = formatAdminURL({\n adminRoute: config.routes.admin,\n path: `${config.admin.routes.reset}/${token}`,\n serverURL,\n })\n let html = `${req.t('authentication:youAreReceivingResetPassword')}\n <a href=\"${forgotURL}\">${forgotURL}</a>\n ${req.t('authentication:youDidNotRequestPassword')}`\n\n if (typeof collectionConfig.auth.forgotPassword?.generateEmailHTML === 'function') {\n html = await collectionConfig.auth.forgotPassword.generateEmailHTML({\n req,\n token,\n user,\n })\n }\n\n let subject = req.t('authentication:resetYourPassword')\n\n if (typeof collectionConfig.auth.forgotPassword?.generateEmailSubject === 'function') {\n subject = await collectionConfig.auth.forgotPassword.generateEmailSubject({\n req,\n token,\n user,\n })\n }\n\n await email.sendEmail({\n from: `\"${email.defaultFromName}\" <${email.defaultFromAddress}>`,\n html,\n subject,\n to: user.email,\n })\n }\n\n // /////////////////////////////////////\n // afterForgotPassword - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterForgotPassword?.length) {\n for (const hook of collectionConfig.hooks.afterForgotPassword) {\n await hook({ args, collection: args.collection?.config, context: req.context })\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n token = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'forgotPassword',\n result: token,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return token\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["crypto","status","httpStatus","URL","buildAfterOperation","buildBeforeOperation","APIError","Forbidden","appendNonTrashedFilter","commitTransaction","formatAdminURL","initTransaction","killTransaction","getLoginOptions","forgotPasswordOperation","incomingArgs","loginWithUsername","collection","config","auth","data","canLoginWithEmail","canLoginWithUsername","sanitizedEmail","email","toLowerCase","trim","sanitizedUsername","username","args","disableLocalStrategy","req","t","BAD_REQUEST","shouldCommit","operation","collectionConfig","disableEmail","expiration","payload","token","randomBytes","toString","whereConstraint","equals","enableTrash","trash","where","user","db","findOne","slug","resetPasswordExpiration","Date","now","forgotPassword","toISOString","update","id","resetPasswordToken","protocol","url","serverURL","headers","get","forgotURL","adminRoute","routes","admin","path","reset","html","generateEmailHTML","subject","generateEmailSubject","sendEmail","from","defaultFromName","defaultFromAddress","to","hooks","afterForgotPassword","length","hook","context","result","error"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,SAASC,UAAUC,UAAU,QAAQ,cAAa;AAClD,SAASC,GAAG,QAAQ,MAAK;AASzB,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,wBAAuB;AAcvD,OAAO,MAAMC,0BAA0B,OACrCC;IAEA,MAAMC,oBAAoBD,aAAaE,UAAU,CAACC,MAAM,CAACC,IAAI,CAACH,iBAAiB;IAC/E,MAAM,EAAEI,IAAI,EAAE,GAAGL;IAEjB,MAAM,EAAEM,iBAAiB,EAAEC,oBAAoB,EAAE,GAAGT,gBAAgBG;IAEpE,MAAMO,iBACJ,AAACF,qBAAqB,AAACN,CAAAA,aAAaK,IAAI,CAACI,KAAK,IAAI,EAAC,EAAGC,WAAW,GAAGC,IAAI,MAAO;IACjF,MAAMC,oBACJ,cAAcP,QAAQ,OAAOA,MAAMQ,aAAa,WAC5CR,KAAKQ,QAAQ,CAACH,WAAW,GAAGC,IAAI,KAChC;IAEN,IAAIG,OAAOd;IAEX,IAAIA,aAAaE,UAAU,CAACC,MAAM,CAACC,IAAI,CAACW,oBAAoB,EAAE;QAC5D,MAAM,IAAIvB,UAAUQ,aAAagB,GAAG,CAACC,CAAC;IACxC;IACA,IAAI,CAACT,kBAAkB,CAACI,mBAAmB;QACzC,MAAM,IAAIrB,SACR,CAAC,QAAQ,EAAEU,oBAAoB,aAAa,QAA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|
|
1
|
+
{"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACV,sBAAsB,EACvB,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AAwBjE,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,cAAc,IAAI;IACpD,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE,gCAAgC,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAA;IACtD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED,KAAK,wBAAwB,GAAG;IAC9B,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,GAAG,CAAA;CACV,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,0CAI9B,wBAAwB,SAQ1B,CAAA;AAED,eAAO,MAAM,cAAc,GAAU,KAAK,SAAS,cAAc,gBACjD,SAAS,CAAC,KAAK,CAAC,KAC7B,OAAO,CAAC;IAAE,IAAI,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAA;CAAE,GAAG,MAAM,CA2U1D,CAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { buildAfterOperation } from '../../collections/operations/
|
|
1
|
+
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
|
|
2
|
+
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
|
|
2
3
|
import { AuthenticationError, LockedAuth, UnverifiedEmail, ValidationError } from '../../errors/index.js';
|
|
3
4
|
import { afterRead } from '../../fields/hooks/afterRead/index.js';
|
|
4
5
|
import { Forbidden } from '../../index.js';
|
|
@@ -34,17 +35,11 @@ export const loginOperation = async (incomingArgs)=>{
|
|
|
34
35
|
// /////////////////////////////////////
|
|
35
36
|
// beforeOperation - Collection
|
|
36
37
|
// /////////////////////////////////////
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
context: args.req.context,
|
|
43
|
-
operation: 'login',
|
|
44
|
-
req: args.req
|
|
45
|
-
}) || args;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
38
|
+
args = await buildBeforeOperation({
|
|
39
|
+
args,
|
|
40
|
+
collection: args.collection.config,
|
|
41
|
+
operation: 'login'
|
|
42
|
+
});
|
|
48
43
|
const { collection: { config: collectionConfig }, data, depth, overrideAccess, req, req: { fallbackLocale, locale, payload, payload: { secret } }, showHiddenFields } = args;
|
|
49
44
|
// /////////////////////////////////////
|
|
50
45
|
// Login
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport {\n AuthenticationError,\n LockedAuth,\n UnverifiedEmail,\n ValidationError,\n} from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Result = {\n exp?: number\n token?: string\n user?: TypedUser\n}\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: any\n}\n\n/**\n * Throws an error if the user is locked or does not exist.\n * This does not check the login attempts, only the lock status. Whoever increments login attempts\n * is responsible for locking the user properly, not whoever checks the login permission.\n */\nexport const checkLoginPermission = ({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs) => {\n if (!user) {\n throw new AuthenticationError(req.t, Boolean(loggingInWithUsername))\n }\n\n if (isUserLocked(new Date(user.lockUntil))) {\n throw new LockedAuth(req.t)\n }\n}\n\nexport const loginOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> => {\n let args = incomingArgs\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n if (args.collection.config.hooks?.beforeOperation?.length) {\n for (const hook of args.collection.config.hooks.beforeOperation) {\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'login',\n req: args.req,\n })) || args\n }\n }\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req,\n req: {\n fallbackLocale,\n locale,\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'username' }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'email' }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { message: req.i18n.t('validation:required'), path: 'email' },\n { message: req.i18n.t('validation:required'), path: 'username' },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'password' }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n // Exclude trashed users\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as TypedUser\n\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const authResult = await authenticateLocalStrategy({ doc: user, password })\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n payload: req.payload,\n req,\n user,\n })\n\n // Re-check login permissions and max attempts after incrementing attempts, in case parallel updates occurred\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (collectionConfig.auth.verify && user._verified === false) {\n throw new UnverifiedEmail({ t: req.t })\n }\n\n /*\n * Correct password accepted - re‑check that the account didn't\n * get locked by parallel bad attempts in the meantime.\n */\n if (maxLoginAttemptsEnabled) {\n const { lockUntil, loginAttempts } = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n select: {\n lockUntil: true,\n loginAttempts: true,\n },\n where: { id: { equals: user.id } },\n }))!\n\n user.lockUntil = lockUntil\n user.loginAttempts = loginAttempts\n\n checkLoginPermission({\n req,\n user,\n })\n }\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: sanitizedEmail!,\n user,\n }\n\n const { sid } = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { exp, token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n user = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: user,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n req,\n showHiddenFields: showHiddenFields!,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n exp,\n token,\n user,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","afterRead","Forbidden","appendNonTrashedFilter","killTransaction","sanitizeInternalFields","getFieldsToSign","getLoginOptions","isUserLocked","jwtSign","addSessionToUser","authenticateLocalStrategy","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","hooks","beforeOperation","length","hook","context","operation","collectionConfig","data","depth","overrideAccess","fallbackLocale","locale","payload","secret","showHiddenFields","email","unsanitizedEmail","password","loginWithUsername","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithEmail","canLoginWithUsername","slug","errors","message","i18n","path","whereConstraint","emailConstraint","equals","usernameConstraint","or","enableTrash","trash","where","db","findOne","_strategy","authResult","doc","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","loginAttempts","select","id","fieldsToSignArgs","sid","fieldsToSign","beforeLogin","exp","token","tokenExpiration","afterLogin","draft","undefined","global","result","error"],"mappings":"AAQA,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,mBAAmB,EACnBC,UAAU,EACVC,eAAe,EACfC,eAAe,QACV,wBAAuB;AAC9B,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,YAAY,QAAQ,qBAAoB;AACjD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,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WAAW8B,QAAQ;YAC7C,KAAK,MAAMC,QAAQG,iBAAiBN,KAAK,CAAC5B,SAAS,CAAE;gBACnDgB,OACE,AAAC,MAAMe,KAAK;oBACVP,YAAYD,KAAKC,UAAU,EAAEC;oBAC7BO,SAASjB,IAAIiB,OAAO;oBACpBuC,KAAKvD;oBACLD;gBACF,MAAOC;YACX;QACF;QAEA,IAAI0E,SAA2D;YAC7DP;YACAC;YACApE;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExC0E,SAAS,MAAM/F,oBAAoB;YACjC4B;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BQ,WAAW;YACXyD;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,MAAMxF,gBAAgBoB,KAAKR,GAAG;QAC9B,MAAM4E;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport {\n AuthenticationError,\n LockedAuth,\n UnverifiedEmail,\n ValidationError,\n} from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Result = {\n exp?: number\n token?: string\n user?: TypedUser\n}\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: any\n}\n\n/**\n * Throws an error if the user is locked or does not exist.\n * This does not check the login attempts, only the lock status. Whoever increments login attempts\n * is responsible for locking the user properly, not whoever checks the login permission.\n */\nexport const checkLoginPermission = ({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs) => {\n if (!user) {\n throw new AuthenticationError(req.t, Boolean(loggingInWithUsername))\n }\n\n if (isUserLocked(new Date(user.lockUntil))) {\n throw new LockedAuth(req.t)\n }\n}\n\nexport const loginOperation = async <TSlug extends CollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> => {\n let args = incomingArgs\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'login',\n })\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req,\n req: {\n fallbackLocale,\n locale,\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'username' }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'email' }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { message: req.i18n.t('validation:required'), path: 'email' },\n { message: req.i18n.t('validation:required'), path: 'username' },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'password' }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n // Exclude trashed users\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as TypedUser\n\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const authResult = await authenticateLocalStrategy({ doc: user, password })\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n payload: req.payload,\n req,\n user,\n })\n\n // Re-check login permissions and max attempts after incrementing attempts, in case parallel updates occurred\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (collectionConfig.auth.verify && user._verified === false) {\n throw new UnverifiedEmail({ t: req.t })\n }\n\n /*\n * Correct password accepted - re‑check that the account didn't\n * get locked by parallel bad attempts in the meantime.\n */\n if (maxLoginAttemptsEnabled) {\n const { lockUntil, loginAttempts } = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n select: {\n lockUntil: true,\n loginAttempts: true,\n },\n where: { id: { equals: user.id } },\n }))!\n\n user.lockUntil = lockUntil\n user.loginAttempts = loginAttempts\n\n checkLoginPermission({\n req,\n user,\n })\n }\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: sanitizedEmail!,\n user,\n }\n\n const { sid } = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { exp, token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n user = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: user,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n req,\n showHiddenFields: showHiddenFields!,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: req.context,\n doc: user,\n req,\n })) || user\n }\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n exp,\n token,\n user,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","afterRead","Forbidden","appendNonTrashedFilter","killTransaction","sanitizeInternalFields","getFieldsToSign","getLoginOptions","isUserLocked","jwtSign","addSessionToUser","authenticateLocalStrategy","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","operation","collectionConfig","data","depth","overrideAccess","fallbackLocale","locale","payload","secret","showHiddenFields","email","unsanitizedEmail","password","loginWithUsername","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithEmail","canLoginWithUsername","slug","errors","message","i18n","path","whereConstraint","emailConstraint","equals","usernameConstraint","or","enableTrash","trash","where","db","findOne","_strategy","authResult","doc","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","loginAttempts","select","id","fieldsToSignArgs","sid","fieldsToSign","hooks","beforeLogin","length","hook","context","exp","token","tokenExpiration","afterLogin","draft","undefined","global","result","error"],"mappings":"AAQA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SACEC,mBAAmB,EACnBC,UAAU,EACVC,eAAe,EACfC,eAAe,QACV,wBAAuB;AAC9B,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,YAAY,QAAQ,qBAAoB;AACjD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SAASC,sBAAsB,QAAQ,gDAA+C;AACtF,SAASC,kBAAkB,QAAQ,4CAA2C;AAuB9E;;;;CAIC,GACD,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,qBAAqB,EACrBC,GAAG,EACHC,IAAI,EACqB;IACzB,IAAI,CAACA,MAAM;Q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ACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,MAAMvF,gBAAgBoB,KAAKR,GAAG;QAC9B,MAAM2E;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/refresh.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/refresh.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAYpE,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,gBAAgB,iBAAwB,SAAS,KAAG,OAAO,CAAC,MAAM,CAsK9E,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import url from 'url';
|
|
2
|
-
import { buildAfterOperation } from '../../collections/operations/
|
|
2
|
+
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
|
|
3
|
+
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
|
|
3
4
|
import { Forbidden } from '../../errors/index.js';
|
|
4
5
|
import { commitTransaction } from '../../utilities/commitTransaction.js';
|
|
5
6
|
import { initTransaction } from '../../utilities/initTransaction.js';
|
|
@@ -14,17 +15,11 @@ export const refreshOperation = async (incomingArgs)=>{
|
|
|
14
15
|
// /////////////////////////////////////
|
|
15
16
|
// beforeOperation - Collection
|
|
16
17
|
// /////////////////////////////////////
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
context: args.req.context,
|
|
23
|
-
operation: 'refresh',
|
|
24
|
-
req: args.req
|
|
25
|
-
}) || args;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
18
|
+
args = await buildBeforeOperation({
|
|
19
|
+
args,
|
|
20
|
+
collection: args.collection.config,
|
|
21
|
+
operation: 'refresh'
|
|
22
|
+
});
|
|
28
23
|
// /////////////////////////////////////
|
|
29
24
|
// Refresh
|
|
30
25
|
// /////////////////////////////////////
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/refresh.ts"],"sourcesContent":["import url from 'url'\n\nimport type { Collection } from '../../collections/config/types.js'\nimport type { Document, PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { Forbidden } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { removeExpiredSessions } from '../sessions.js'\n\nexport type Result = {\n exp: number\n refreshedToken: string\n setCookie?: boolean\n /** @deprecated\n * use:\n * ```ts\n * user._strategy\n * ```\n */\n strategy?: string\n user: Document\n}\n\nexport type Arguments = {\n collection: Collection\n req: PayloadRequest\n}\n\nexport const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => {\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n if (args.collection.config.hooks?.beforeOperation?.length) {\n for (const hook of args.collection.config.hooks.beforeOperation) {\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'refresh',\n req: args.req,\n })) || args\n }\n }\n\n // /////////////////////////////////////\n // Refresh\n // /////////////////////////////////////\n\n const {\n collection: { config: collectionConfig },\n req,\n req: {\n payload: { config, secret },\n },\n } = args\n\n if (!args.req.user) {\n throw new Forbidden(args.req.t)\n }\n\n const parsedURL = url.parse(args.req.url!)\n const isGraphQL = parsedURL.pathname === config.routes.graphQL\n\n let user = await req.payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: args.req.user.id } },\n })\n\n const sid = args.req.user._sid\n\n if (collectionConfig.auth.useSessions && !collectionConfig.auth.disableLocalStrategy) {\n if (!Array.isArray(user.sessions) || !sid) {\n throw new Forbidden(args.req.t)\n }\n\n const existingSession = user.sessions.find(({ id }: { id: number }) => id === sid)\n\n const now = new Date()\n const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000\n existingSession.expiresAt = new Date(now.getTime() + tokenExpInMs)\n\n // Prevent updatedAt from being updated when only refreshing a session\n user.updatedAt = null\n\n await req.payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n sessions: removeExpiredSessions(user.sessions),\n },\n req,\n returning: false,\n })\n }\n\n user = await req.payload.findByID({\n id: user.id,\n collection: collectionConfig.slug,\n depth: isGraphQL ? 0 : args.collection.config.auth.depth,\n req: args.req,\n })\n\n if (user) {\n user.collection = args.req.user.collection\n user._strategy = args.req.user._strategy\n }\n\n let result!: Result\n\n // /////////////////////////////////////\n // refresh hook - Collection\n // /////////////////////////////////////\n\n for (const refreshHook of args.collection.config.hooks.refresh) {\n const hookResult = await refreshHook({ args, user })\n\n if (hookResult) {\n result = hookResult\n break\n }\n }\n\n if (!result) {\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: user?.email as string,\n sid,\n user: args?.req?.user,\n })\n\n const { exp, token: refreshedToken } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n result = {\n exp,\n refreshedToken,\n setCookie: true,\n /** @deprecated\n * use:\n * ```ts\n * user._strategy\n * ```\n */\n strategy: args.req.user._strategy,\n user,\n }\n }\n\n // /////////////////////////////////////\n // After Refresh - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRefresh?.length) {\n for (const hook of collectionConfig.hooks.afterRefresh) {\n result =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n exp: result.exp,\n req: args.req,\n token: result.refreshedToken,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'refresh',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["url","buildAfterOperation","Forbidden","commitTransaction","initTransaction","killTransaction","getFieldsToSign","jwtSign","removeExpiredSessions","refreshOperation","incomingArgs","args","shouldCommit","req","collection","config","hooks","beforeOperation","length","hook","context","operation","collectionConfig","payload","secret","user","t","parsedURL","parse","isGraphQL","pathname","routes","graphQL","db","findOne","slug","where","id","equals","sid","_sid","auth","useSessions","disableLocalStrategy","Array","isArray","sessions","existingSession","find","now","Date","tokenExpInMs","tokenExpiration","expiresAt","getTime","updatedAt","updateOne","data","returning","findByID","depth","_strategy","result","refreshHook","refresh","hookResult","fieldsToSign","email","exp","token","refreshedToken","setCookie","strategy","afterRefresh","error"],"mappings":"AAAA,OAAOA,SAAS,MAAK;AAKrB,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAA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QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,IAAIlD,cAAc;YAChB,MAAMT,kBAAkBU;QAC1B;QAEA,OAAOiD;IACT,EAAE,OAAOY,OAAgB;QACvB,MAAMrE,gBAAgBM,KAAKE,GAAG;QAC9B,MAAM6D;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/refresh.ts"],"sourcesContent":["import url from 'url'\n\nimport type { Collection } from '../../collections/config/types.js'\nimport type { Document, PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { Forbidden } from '../../errors/index.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { removeExpiredSessions } from '../sessions.js'\n\nexport type Result = {\n exp: number\n refreshedToken: string\n setCookie?: boolean\n /** @deprecated\n * use:\n * ```ts\n * user._strategy\n * ```\n */\n strategy?: string\n user: Document\n}\n\nexport type Arguments = {\n collection: Collection\n req: PayloadRequest\n}\n\nexport const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => {\n let args = incomingArgs\n\n try {\n const shouldCommit = await initTransaction(args.req)\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'refresh',\n })\n\n // /////////////////////////////////////\n // Refresh\n // /////////////////////////////////////\n\n const {\n collection: { config: collectionConfig },\n req,\n req: {\n payload: { config, secret },\n },\n } = args\n\n if (!args.req.user) {\n throw new Forbidden(args.req.t)\n }\n\n const parsedURL = url.parse(args.req.url!)\n const isGraphQL = parsedURL.pathname === config.routes.graphQL\n\n let user = await req.payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: args.req.user.id } },\n })\n\n const sid = args.req.user._sid\n\n if (collectionConfig.auth.useSessions && !collectionConfig.auth.disableLocalStrategy) {\n if (!Array.isArray(user.sessions) || !sid) {\n throw new Forbidden(args.req.t)\n }\n\n const existingSession = user.sessions.find(({ id }: { id: number }) => id === sid)\n\n const now = new Date()\n const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000\n existingSession.expiresAt = new Date(now.getTime() + tokenExpInMs)\n\n // Prevent updatedAt from being updated when only refreshing a session\n user.updatedAt = null\n\n await req.payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n sessions: removeExpiredSessions(user.sessions),\n },\n req,\n returning: false,\n })\n }\n\n user = await req.payload.findByID({\n id: user.id,\n collection: collectionConfig.slug,\n depth: isGraphQL ? 0 : args.collection.config.auth.depth,\n req: args.req,\n })\n\n if (user) {\n user.collection = args.req.user.collection\n user._strategy = args.req.user._strategy\n }\n\n let result!: Result\n\n // /////////////////////////////////////\n // refresh hook - Collection\n // /////////////////////////////////////\n\n for (const refreshHook of args.collection.config.hooks.refresh) {\n const hookResult = await refreshHook({ args, user })\n\n if (hookResult) {\n result = hookResult\n break\n }\n }\n\n if (!result) {\n const fieldsToSign = getFieldsToSign({\n collectionConfig,\n email: user?.email as string,\n sid,\n user: args?.req?.user,\n })\n\n const { exp, token: refreshedToken } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n result = {\n exp,\n refreshedToken,\n setCookie: true,\n /** @deprecated\n * use:\n * ```ts\n * user._strategy\n * ```\n */\n strategy: args.req.user._strategy,\n user,\n }\n }\n\n // /////////////////////////////////////\n // After Refresh - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRefresh?.length) {\n for (const hook of collectionConfig.hooks.afterRefresh) {\n result =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n exp: result.exp,\n req: args.req,\n token: result.refreshedToken,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'refresh',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return result\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["url","buildAfterOperation","buildBeforeOperation","Forbidden","commitTransaction","initTransaction","killTransaction","getFieldsToSign","jwtSign","removeExpiredSessions","refreshOperation","incomingArgs","args","shouldCommit","req","collection","config","operation","collectionConfig","payload","secret","user","t","parsedURL","parse","isGraphQL","pathname","routes","graphQL","db","findOne","slug","where","id","equals","sid","_sid","auth","useSessions","disableLocalStrategy","Array","isArray","sessions","existingSession","find","now","Date","tokenExpInMs","tokenExpiration","expiresAt","getTime","updatedAt","updateOne","data","returning","findByID","depth","_strategy","result","refreshHook","hooks","refresh","hookResult","fieldsToSign","email","exp","token","refreshedToken","setCookie","strategy","afterRefresh","length","hook","context","error"],"mappings":"AAAA,OAAOA,SAAS,MAAK;AAKrB,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,qBAAqB,QAAQ,iBAAgB;AAqBtD,OAAO,MAAMC,mBAAmB,OAAOC;IACrC,IAAIC,OAAOD;IAEX,IAAI;QACF,MAAME,eAAe,MAAMR,gBAAgBO,KAAKE,GAAG;QAEnD,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExCF,OAAO,MAAMV,qBAAqB;YAChCU;YACAG,YAAY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ACAC,WAAW;gBACX;;;;;SAKC,GACDC,UAAUzD,KAAKE,GAAG,CAACO,IAAI,CAACoC,SAAS;gBACjCpC;YACF;QACF;QAEA,wCAAwC;QACxC,6BAA6B;QAC7B,wCAAwC;QAExC,IAAIH,iBAAiB0C,KAAK,EAAEU,cAAcC,QAAQ;YAChD,KAAK,MAAMC,QAAQtD,iBAAiB0C,KAAK,CAACU,YAAY,CAAE;gBACtDZ,SACE,AAAC,MAAMc,KAAK;oBACVzD,YAAYH,KAAKG,UAAU,EAAEC;oBAC7ByD,SAAS7D,KAAKE,GAAG,CAAC2D,OAAO;oBACzBR,KAAKP,OAAOO,GAAG;oBACfnD,KAAKF,KAAKE,GAAG;oBACboD,OAAOR,OAAOS,cAAc;gBAC9B,MAAOT;YACX;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCA,SAAS,MAAMzD,oBAAoB;YACjCW;YACAG,YAAYH,KAAKG,UAAU,EAAEC;YAC7BC,WAAW;YACXyC;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,IAAI7C,cAAc;YAChB,MAAMT,kBAAkBU;QAC1B;QAEA,OAAO4C;IACT,EAAE,OAAOgB,OAAgB;QACvB,MAAMpE,gBAAgBM,KAAKE,GAAG;QAC9B,MAAM4D;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAe1D,MAAM,MAAM,MAAM,GAAG;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC9B,CAAA;AAED,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE;QACJ,QAAQ,EAAE,MAAM,CAAA;QAChB,KAAK,EAAE,MAAM,CAAA;KACd,CAAA;IACD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAU,KAAK,SAAS,cAAc,QACjE,SAAS,KACd,OAAO,CAAC,MAAM,CA4MhB,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { status as httpStatus } from 'http-status';
|
|
2
|
-
import { buildAfterOperation } from '../../collections/operations/
|
|
2
|
+
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
|
|
3
|
+
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
|
|
3
4
|
import { APIError, Forbidden } from '../../errors/index.js';
|
|
4
5
|
import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
|
|
5
6
|
import { commitTransaction } from '../../utilities/commitTransaction.js';
|
|
@@ -20,17 +21,11 @@ export const resetPasswordOperation = async (args)=>{
|
|
|
20
21
|
}
|
|
21
22
|
try {
|
|
22
23
|
const shouldCommit = await initTransaction(req);
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
context: args.req.context,
|
|
29
|
-
operation: 'resetPassword',
|
|
30
|
-
req: args.req
|
|
31
|
-
}) || args;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
24
|
+
args = await buildBeforeOperation({
|
|
25
|
+
args,
|
|
26
|
+
collection: args.collection.config,
|
|
27
|
+
operation: 'resetPassword'
|
|
28
|
+
});
|
|
34
29
|
// /////////////////////////////////////
|
|
35
30
|
// Reset Password
|
|
36
31
|
// /////////////////////////////////////
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utils.js'\nimport { APIError, Forbidden } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends CollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n try {\n const shouldCommit = await initTransaction(req)\n\n if (args.collection.config.hooks?.beforeOperation?.length) {\n for (const hook of args.collection.config.hooks.beforeOperation) {\n args =\n (await hook({\n args,\n collection: args.collection?.config,\n context: args.req.context,\n operation: 'resetPassword',\n req: args.req,\n })) || args\n }\n }\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n const user = await payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({ doc, password: data.password })\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email,\n user,\n }\n\n const { sid } = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n let userBeforeLogin = user\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n userBeforeLogin =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user: userBeforeLogin,\n })) || userBeforeLogin\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = userBeforeLogin\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n userBeforeLogin =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user: userBeforeLogin,\n })) || userBeforeLogin\n }\n }\n\n const fullUser = await payload.findByID({\n id: user.id,\n collection: collectionConfig.slug,\n depth,\n overrideAccess,\n req,\n trash: false,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n if (fullUser) {\n fullUser.collection = collectionConfig.slug\n fullUser._strategy = 'local-jwt'\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: fullUser,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n result,\n })\n\n return result\n } catch (error: unknown) {\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["status","httpStatus","buildAfterOperation","APIError","Forbidden","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","getFieldsToSign","jwtSign","addSessionToUser","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","shouldCommit","hooks","beforeOperation","length","hook","context","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","hash","salt","password","verify","_verified","beforeValidate","updatedAt","doc","updateOne","id","fieldsToSignArgs","email","sid","fieldsToSign","userBeforeLogin","beforeLogin","tokenExpiration","afterLogin","fullUser","findByID","_strategy","result","error"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAMlD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,QAAQ,EAAEC,SAAS,QAAQ,wBAAuB;AAC3D,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SAASC,wBAAwB,QAAQ,kDAAiD;AAkB1F,OAAO,MAAMC,yBAAyB,OACpCC;IAEA,MAAM,EACJC,YAAY,EAAEC,QAAQC,gBAAgB,EAAE,EACxCC,IAAI,EACJC,KAAK,EACLC,cAAc,EACdC,KAAK,EACHC,SAAS,EAAEC,MAAM,EAAE,EACnBD,OAAO,EACR,EACDD,GAAG,EACJ,GAAGP;IAEJ,IACE,CAACU,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACT,MAAM,YAC5C,CAACM,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACT,MAAM,aAC5C;QACA,MAAM,IAAIhB,SAAS,0BAA0BF,WAAW4B,WAAW;IACrE;IAEA,IAAIX,iBAAiBY,IAAI,CAACC,oBAAoB,EAAE;QAC9C,MAAM,IAAI3B,UAAUkB,IAAIU,CAAC;IAC3B;IAEA,IAAI;QAC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,MAAM,EAAEpB,KAAK,EAAE,GAAG,MAAMxC,QAAQ;YAC9B2D;YACA7C;YACAgD,iBAAiBtD,iBAAiBY,IAAI,CAAC0C,eAAe;QACxD;QAEAlD,IAAI6B,IAAI,GAAGmB;QAEX,wCAAwC;QACxC,0BAA0B;QAC1B,wCAAwC;QAExC,IAAIpD,iBAAiBgB,KAAK,EAAEuC,YAAYrC,QAAQ;YAC9C,KAAK,MAAMC,QAAQnB,iBAAiBgB,KAAK,CAACuC,UAAU,CAAE;gBACpDH,kBACE,AAAC,MAAMjC,KAAK;oBACVrB,YAAYD,KAAKC,UAAU,EAAEC;oBAC7BqB,SAASvB,KAAKO,GAAG,CAACgB,OAAO;oBACzBhB,KAAKP,KAAKO,GAAG;oBACb4B;oBACAC,MAAMmB;gBACR,MAAOA;YACX;QACF;QAEA,MAAMI,WAAW,MAAMnD,QAAQoD,QAAQ,CAAC;YACtCV,IAAId,KAAKc,EAAE;YACXjD,YAAYE,iBAAiBoC,IAAI;YACjClC;YACAC;YACAC;YACAqB,OAAO;QACT;QAEA,IAAIV,cAAc;YAChB,MAAM3B,kBAAkBgB;QAC1B;QAEA,IAAIoD,UAAU;YACZA,SAAS1D,UAAU,GAAGE,iBAAiBoC,IAAI;YAC3CoB,SAASE,SAAS,GAAG;QACvB;QAEA,IAAIC,SAA2D;YAC7D3B;YACAC,MAAMuB;QACR;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCG,SAAS,MAAM3E,oBAAoB;YACjCa;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BsB,WAAW;YACXsC;QACF;QAEA,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,MAAMtE,gBAAgBc;QACtB,MAAMwD;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError, Forbidden } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends CollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n try {\n const shouldCommit = await initTransaction(req)\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'resetPassword',\n })\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n const user = await payload.db.findOne<any>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({ doc, password: data.password })\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email,\n user,\n }\n\n const { sid } = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n let userBeforeLogin = user\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n userBeforeLogin =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user: userBeforeLogin,\n })) || userBeforeLogin\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = userBeforeLogin\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n userBeforeLogin =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user: userBeforeLogin,\n })) || userBeforeLogin\n }\n }\n\n const fullUser = await payload.findByID({\n id: user.id,\n collection: collectionConfig.slug,\n depth,\n overrideAccess,\n req,\n trash: false,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n if (fullUser) {\n fullUser.collection = collectionConfig.slug\n fullUser._strategy = 'local-jwt'\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: fullUser,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n result,\n })\n\n return result\n } catch (error: unknown) {\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["status","httpStatus","buildAfterOperation","buildBeforeOperation","APIError","Forbidden","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","getFieldsToSign","jwtSign","addSessionToUser","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","hash","salt","password","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","doc","updateOne","id","fieldsToSignArgs","email","sid","fieldsToSign","userBeforeLogin","beforeLogin","tokenExpiration","afterLogin","fullUser","findByID","_strategy","result","error"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAMlD,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,QAAQ,wBAAuB;AAC3D,SAASC,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AChB,MAAM3B,kBAAkBgB;QAC1B;QAEA,IAAImD,UAAU;YACZA,SAASzD,UAAU,GAAGE,iBAAiB+B,IAAI;YAC3CwB,SAASE,SAAS,GAAG;QACvB;QAEA,IAAIC,SAA2D;YAC7D/B;YACAC,MAAM2B;QACR;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCG,SAAS,MAAM3E,oBAAoB;YACjCc;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BiB,WAAW;YACX0C;QACF;QAEA,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,MAAMrE,gBAAgBc;QACtB,MAAMuD;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unlock.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/unlock.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACX,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"unlock.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/unlock.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACX,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AAcjE,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,cAAc,IAAI;IACpD,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE,gCAAgC,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAA;IACvD,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,eAAO,MAAM,eAAe,GAAU,KAAK,SAAS,cAAc,QAC1D,SAAS,CAAC,KAAK,CAAC,KACrB,OAAO,CAAC,OAAO,CAmHjB,CAAA"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { status as httpStatus } from 'http-status';
|
|
2
|
+
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
|
|
3
|
+
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
|
|
2
4
|
import { APIError } from '../../errors/index.js';
|
|
3
5
|
import { combineQueries, Forbidden } from '../../index.js';
|
|
4
6
|
import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
|
|
@@ -21,6 +23,11 @@ export const unlockOperation = async (args)=>{
|
|
|
21
23
|
throw new APIError(`Missing ${collectionConfig.auth.loginWithUsername ? 'username' : 'email'}.`, httpStatus.BAD_REQUEST);
|
|
22
24
|
}
|
|
23
25
|
try {
|
|
26
|
+
args = await buildBeforeOperation({
|
|
27
|
+
args,
|
|
28
|
+
collection: args.collection.config,
|
|
29
|
+
operation: 'unlock'
|
|
30
|
+
});
|
|
24
31
|
const shouldCommit = await initTransaction(req);
|
|
25
32
|
let whereConstraint = {};
|
|
26
33
|
// /////////////////////////////////////
|
|
@@ -78,7 +85,13 @@ export const unlockOperation = async (args)=>{
|
|
|
78
85
|
if (shouldCommit) {
|
|
79
86
|
await commitTransaction(req);
|
|
80
87
|
}
|
|
81
|
-
|
|
88
|
+
result = await buildAfterOperation({
|
|
89
|
+
args,
|
|
90
|
+
collection: args.collection.config,
|
|
91
|
+
operation: 'unlock',
|
|
92
|
+
result
|
|
93
|
+
});
|
|
94
|
+
return Boolean(result);
|
|
82
95
|
} catch (error) {
|
|
83
96
|
await killTransaction(req);
|
|
84
97
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/unlock.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { APIError } from '../../errors/index.js'\nimport { combineQueries, Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { executeAccess } from '../executeAccess.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['unlock']\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const unlockOperation = async <TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<boolean> => {\n const {\n collection: { config: collectionConfig },\n overrideAccess,\n req: { locale },\n req,\n } = args\n\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n const sanitizedEmail = canLoginWithEmail && (args.data?.email || '').toLowerCase().trim()\n const sanitizedUsername =\n (canLoginWithUsername &&\n 'username' in args.data &&\n typeof args.data.username === 'string' &&\n args.data.username.toLowerCase().trim()) ||\n null\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${collectionConfig.auth.loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n try {\n const shouldCommit = await initTransaction(req)\n let whereConstraint: Where = {}\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n if (!overrideAccess) {\n const accessResult = await executeAccess({ req }, collectionConfig.access.unlock)\n\n if (accessResult && typeof accessResult === 'object') {\n whereConstraint = accessResult\n }\n }\n\n // /////////////////////////////////////\n // Unlock\n // /////////////////////////////////////\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = combineQueries(whereConstraint, {\n email: {\n equals: sanitizedEmail,\n },\n })\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = combineQueries(whereConstraint, {\n username: {\n equals: sanitizedUsername,\n },\n })\n }\n\n // Exclude trashed users unless `trash: true`\n whereConstraint = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: whereConstraint,\n })\n\n const user = await req.payload.db.findOne({\n collection: collectionConfig.slug,\n locale: locale!,\n req,\n where: whereConstraint,\n })\n\n let result: boolean | null = null\n\n if (user) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n result = true\n } else {\n result = null\n throw new Forbidden(req.t)\n }\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return result\n } catch (error: unknown) {\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["status","httpStatus","APIError","combineQueries","Forbidden","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","executeAccess","getLoginOptions","resetLoginAttempts","unlockOperation","args","collection","config","collectionConfig","overrideAccess","req","locale","loginWithUsername","auth","canLoginWithEmail","canLoginWithUsername","sanitizedEmail","data","email","toLowerCase","trim","sanitizedUsername","username","disableLocalStrategy","t","BAD_REQUEST","shouldCommit","whereConstraint","accessResult","access","unlock","equals","enableTrash","Boolean","trash","where","user","payload","db","findOne","slug","result","doc","error"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AASlD,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,cAAc,EAAEC,SAAS,QAAQ,iBAAgB;AAC1D,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,aAAa,QAAQ,sBAAqB;AACnD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,kBAAkB,QAAQ,4CAA2C;AAS9E,OAAO,MAAMC,kBAAkB,OAC7BC;IAEA,MAAM,EACJC,YAAY,EAAEC,QAAQC,gBAAgB,EAAE,EACxCC,cAAc,EACdC,KAAK,EAAEC,MAAM,EAAE,EACfD,GAAG,EACJ,GAAGL;IAEJ,MAAMO,oBAAoBJ,iBAAiBK,IAAI,CAACD,iBAAiB;IAEjE,MAAM,EAAEE,iBAAiB,EAAEC,oBAAoB,EAAE,GAAGb,gBAAgBU;IAEpE,MAAMI,iBAAiBF,qBAAqB,AAACT,CAAAA,KAAKY,IAAI,EAAEC,SAAS,EAAC,EAAGC,WAAW,GAAGC,IAAI;IACvF,MAAMC,oBACJ,AAACN,wBACC,cAAcV,KAAKY,IAAI,IACvB,OAAOZ,KAAKY,IAAI,CAACK,QAAQ,KAAK,YAC9BjB,KAAKY,IAAI,CAACK,QAAQ,CAACH,WAAW,GAAGC,IAAI,MACvC;IAEF,IAAIZ,iBAAiBK,IAAI,CAACU,oBAAoB,EAAE;QAC9C,MAAM,IAAI3B,UAAUc,IAAIc,CAAC;IAC3B;IACA,IAAI,CAACR,kBAAkB,CAACK,mBAAmB;QACzC,MAAM,IAAI3B,SACR,CAAC,QAAQ,EAAEc,iBAAiBK,IAAI,CAACD,iBAAiB,GAAG,aAAa,QAAQ,CAAC,CAAC,
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/unlock.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type {\n AuthOperationsFromCollectionSlug,\n Collection,\n} from '../../collections/config/types.js'\nimport type { CollectionSlug } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError } from '../../errors/index.js'\nimport { combineQueries, Forbidden } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { executeAccess } from '../executeAccess.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['unlock']\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const unlockOperation = async <TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<boolean> => {\n const {\n collection: { config: collectionConfig },\n overrideAccess,\n req: { locale },\n req,\n } = args\n\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n const sanitizedEmail = canLoginWithEmail && (args.data?.email || '').toLowerCase().trim()\n const sanitizedUsername =\n (canLoginWithUsername &&\n 'username' in args.data &&\n typeof args.data.username === 'string' &&\n args.data.username.toLowerCase().trim()) ||\n null\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n if (!sanitizedEmail && !sanitizedUsername) {\n throw new APIError(\n `Missing ${collectionConfig.auth.loginWithUsername ? 'username' : 'email'}.`,\n httpStatus.BAD_REQUEST,\n )\n }\n\n try {\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'unlock',\n })\n\n const shouldCommit = await initTransaction(req)\n let whereConstraint: Where = {}\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n if (!overrideAccess) {\n const accessResult = await executeAccess({ req }, collectionConfig.access.unlock)\n\n if (accessResult && typeof accessResult === 'object') {\n whereConstraint = accessResult\n }\n }\n\n // /////////////////////////////////////\n // Unlock\n // /////////////////////////////////////\n\n if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = combineQueries(whereConstraint, {\n email: {\n equals: sanitizedEmail,\n },\n })\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = combineQueries(whereConstraint, {\n username: {\n equals: sanitizedUsername,\n },\n })\n }\n\n // Exclude trashed users unless `trash: true`\n whereConstraint = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: whereConstraint,\n })\n\n const user = await req.payload.db.findOne({\n collection: collectionConfig.slug,\n locale: locale!,\n req,\n where: whereConstraint,\n })\n\n let result: boolean | null = null\n\n if (user) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n result = true\n } else {\n result = null\n throw new Forbidden(req.t)\n }\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n result = await buildAfterOperation({\n args,\n collection: args.collection.config,\n operation: 'unlock',\n result,\n })\n\n return Boolean(result)\n } catch (error: unknown) {\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["status","httpStatus","buildAfterOperation","buildBeforeOperation","APIError","combineQueries","Forbidden","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","executeAccess","getLoginOptions","resetLoginAttempts","unlockOperation","args","collection","config","collectionConfig","overrideAccess","req","locale","loginWithUsername","auth","canLoginWithEmail","canLoginWithUsername","sanitizedEmail","data","email","toLowerCase","trim","sanitizedUsername","username","disableLocalStrategy","t","BAD_REQUEST","operation","shouldCommit","whereConstraint","accessResult","access","unlock","equals","enableTrash","Boolean","trash","where","user","payload","db","findOne","slug","result","doc","error"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AASlD,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,cAAc,EAAEC,SAAS,QAAQ,iBAAgB;AAC1D,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe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../../src/collections/config/sanitize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EACV,gBAAgB,EAChB,yBAAyB,EAG1B,MAAM,YAAY,CAAA;AAuBnB,eAAO,MAAM,kBAAkB,WACrB,MAAM,cACF,gBAAgB,iCAKG,KAAK,CAAC,CAAC,MAAM,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,wBAC1D,MAAM,EAAE,KAC7B,OAAO,CAAC,yBAAyB,
|
|
1
|
+
{"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../../src/collections/config/sanitize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACpE,OAAO,KAAK,EACV,gBAAgB,EAChB,yBAAyB,EAG1B,MAAM,YAAY,CAAA;AAuBnB,eAAO,MAAM,kBAAkB,WACrB,MAAM,cACF,gBAAgB,iCAKG,KAAK,CAAC,CAAC,MAAM,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,wBAC1D,MAAM,EAAE,KAC7B,OAAO,CAAC,yBAAyB,CAsPnC,CAAA"}
|
|
@@ -151,6 +151,8 @@ export const sanitizeCollection = async (config, collection, /**
|
|
|
151
151
|
}
|
|
152
152
|
sanitized.fields = mergeBaseFields(sanitized.fields, baseVersionFields);
|
|
153
153
|
}
|
|
154
|
+
} else {
|
|
155
|
+
delete sanitized.versions;
|
|
154
156
|
}
|
|
155
157
|
if (sanitized.folders === true) {
|
|
156
158
|
sanitized.folders = {
|