payload 4.0.0-beta.8 → 4.0.0-beta.9
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/baseFields/sessions.d.ts.map +1 -1
- package/dist/auth/baseFields/sessions.js +12 -0
- package/dist/auth/baseFields/sessions.js.map +1 -1
- package/dist/auth/createAuthToken.d.ts +3 -3
- package/dist/auth/createAuthToken.d.ts.map +1 -1
- package/dist/auth/createAuthToken.js +4 -1
- package/dist/auth/createAuthToken.js.map +1 -1
- package/dist/auth/getUserAgentLabel.d.ts +8 -0
- package/dist/auth/getUserAgentLabel.d.ts.map +1 -0
- package/dist/auth/getUserAgentLabel.js +70 -0
- package/dist/auth/getUserAgentLabel.js.map +1 -0
- package/dist/auth/operations/login.d.ts.map +1 -1
- package/dist/auth/operations/login.js +5 -0
- package/dist/auth/operations/login.js.map +1 -1
- package/dist/auth/operations/resetPassword.d.ts.map +1 -1
- package/dist/auth/operations/resetPassword.js +5 -0
- package/dist/auth/operations/resetPassword.js.map +1 -1
- package/dist/auth/sessions.d.ts +2 -2
- package/dist/auth/sessions.d.ts.map +1 -1
- package/dist/auth/sessions.js +5 -2
- package/dist/auth/sessions.js.map +1 -1
- package/dist/auth/types.d.ts +9 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.d.ts.map +1 -1
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.js +7 -3
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.js.map +1 -1
- package/dist/collections/operations/create.js +1 -1
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/findByID.d.ts.map +1 -1
- package/dist/collections/operations/findByID.js +1 -3
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/collections/operations/local/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/local/restoreVersion.js +2 -1
- package/dist/collections/operations/local/restoreVersion.js.map +1 -1
- package/dist/collections/operations/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/restoreVersion.js +22 -6
- package/dist/collections/operations/restoreVersion.js.map +1 -1
- package/dist/collections/operations/update.js +1 -1
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -1
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/exports/internal.d.ts +1 -1
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js.map +1 -1
- package/dist/index.bundled.d.ts +48 -63
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/uploads/checkFileAccess.d.ts.map +1 -1
- package/dist/uploads/checkFileAccess.js +1 -0
- package/dist/uploads/checkFileAccess.js.map +1 -1
- package/dist/uploads/endpoints/getFile.d.ts.map +1 -1
- package/dist/uploads/endpoints/getFile.js +17 -5
- package/dist/uploads/endpoints/getFile.js.map +1 -1
- package/dist/uploads/fileSelectionParams.d.ts +10 -0
- package/dist/uploads/fileSelectionParams.d.ts.map +1 -0
- package/dist/uploads/fileSelectionParams.js +10 -0
- package/dist/uploads/fileSelectionParams.js.map +1 -0
- package/dist/uploads/fileVersioning/cloudStorage.d.ts +7 -0
- package/dist/uploads/fileVersioning/cloudStorage.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.js +43 -19
- package/dist/uploads/fileVersioning/cloudStorage.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts +18 -4
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js +73 -30
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/fileVersioning/restore.d.ts +17 -3
- package/dist/uploads/fileVersioning/restore.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restore.js +42 -1
- package/dist/uploads/fileVersioning/restore.js.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts +15 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts.map +1 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.js +176 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.js.map +1 -0
- package/dist/uploads/fileVersioning/storedFiles.d.ts +4 -0
- package/dist/uploads/fileVersioning/storedFiles.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.js +10 -1
- package/dist/uploads/fileVersioning/storedFiles.js.map +1 -1
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.d.ts +122 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.d.ts.map +1 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.js +261 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.js.map +1 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.d.ts +30 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.d.ts.map +1 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.js +131 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.js.map +1 -0
- package/dist/uploads/generateFileData/index.d.ts +47 -0
- package/dist/uploads/generateFileData/index.d.ts.map +1 -0
- package/dist/uploads/generateFileData/index.js +365 -0
- package/dist/uploads/generateFileData/index.js.map +1 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.d.ts +52 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.js +394 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.js.map +1 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.d.ts +33 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.js +100 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.js.map +1 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.d.ts +20 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.js +20 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.js.map +1 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.d.ts +35 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.d.ts.map +1 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.js +54 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.js.map +1 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.d.ts +44 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.d.ts.map +1 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.js +63 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.js.map +1 -0
- package/dist/uploads/generateFileData/runUploadTransformers.d.ts +46 -0
- package/dist/uploads/generateFileData/runUploadTransformers.d.ts.map +1 -0
- package/dist/uploads/generateFileData/runUploadTransformers.js +93 -0
- package/dist/uploads/generateFileData/runUploadTransformers.js.map +1 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.d.ts +32 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.js +43 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.js.map +1 -0
- package/dist/uploads/generateFileData/source/readUploadSource.d.ts +27 -0
- package/dist/uploads/generateFileData/source/readUploadSource.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/readUploadSource.js +97 -0
- package/dist/uploads/generateFileData/source/readUploadSource.js.map +1 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.d.ts +50 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.js +42 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.js.map +1 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.d.ts +9 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.js +19 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.js.map +1 -0
- package/dist/uploads/generateFileData/utils/generateImageSizeFilename.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/generateImageSizeFilename.js.map +1 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.d.ts +27 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.js +22 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.js.map +1 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.d.ts +11 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.js +15 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.js.map +1 -0
- package/dist/uploads/getFileFromUploadInstructions.js +2 -2
- package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
- package/dist/uploads/requestTimeFileData.d.ts +36 -0
- package/dist/uploads/requestTimeFileData.d.ts.map +1 -0
- package/dist/uploads/requestTimeFileData.js +56 -0
- package/dist/uploads/requestTimeFileData.js.map +1 -0
- package/dist/uploads/transformState/planUpload.d.ts +27 -2
- package/dist/uploads/transformState/planUpload.d.ts.map +1 -1
- package/dist/uploads/transformState/planUpload.js +27 -4
- package/dist/uploads/transformState/planUpload.js.map +1 -1
- package/dist/uploads/transformState/transformStateInput.d.ts +52 -0
- package/dist/uploads/transformState/transformStateInput.d.ts.map +1 -0
- package/dist/uploads/transformState/transformStateInput.js +113 -0
- package/dist/uploads/transformState/transformStateInput.js.map +1 -0
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts +7 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts.map +1 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.js +40 -10
- package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
- package/dist/uploads/transformers/transformUploadFile.js +1 -1
- package/dist/uploads/transformers/transformUploadFile.js.map +1 -1
- package/dist/uploads/transformers/uploadTransformerBridge.d.ts +16 -6
- package/dist/uploads/transformers/uploadTransformerBridge.d.ts.map +1 -1
- package/dist/uploads/transformers/uploadTransformerBridge.js +3 -1
- package/dist/uploads/transformers/uploadTransformerBridge.js.map +1 -1
- package/dist/utilities/initTransaction.d.ts.map +1 -1
- package/dist/utilities/initTransaction.js +35 -7
- package/dist/utilities/initTransaction.js.map +1 -1
- package/dist/versions/getLatestCollectionVersion.d.ts +1 -2
- package/dist/versions/getLatestCollectionVersion.d.ts.map +1 -1
- package/dist/versions/getLatestCollectionVersion.js +7 -23
- package/dist/versions/getLatestCollectionVersion.js.map +1 -1
- package/dist/versions/getLatestGlobalVersion.d.ts +1 -2
- package/dist/versions/getLatestGlobalVersion.d.ts.map +1 -1
- package/dist/versions/getLatestGlobalVersion.js +2 -6
- package/dist/versions/getLatestGlobalVersion.js.map +1 -1
- package/package.json +3 -3
- package/skills/payload/SKILL.md +12 -9
- package/skills/payload/reference/ADAPTERS.md +21 -27
- package/skills/payload/reference/FIELDS.md +1 -1
- package/skills/payload/reference/HOOKS.md +1 -1
- package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +1 -1
- package/skills/payload/reference/QUERIES.md +6 -6
- package/dist/uploads/generateFileData.d.ts +0 -60
- package/dist/uploads/generateFileData.d.ts.map +0 -1
- package/dist/uploads/generateFileData.js +0 -1022
- package/dist/uploads/generateFileData.js.map +0 -1
- package/dist/uploads/generateImageSizeFilename.d.ts.map +0 -1
- package/dist/uploads/generateImageSizeFilename.js.map +0 -1
- package/dist/uploads/transformState/resolveUploadEdits.d.ts +0 -91
- package/dist/uploads/transformState/resolveUploadEdits.d.ts.map +0 -1
- package/dist/uploads/transformState/resolveUploadEdits.js +0 -397
- package/dist/uploads/transformState/resolveUploadEdits.js.map +0 -1
- /package/dist/uploads/{generateImageSizeFilename.d.ts → generateFileData/utils/generateImageSizeFilename.d.ts} +0 -0
- /package/dist/uploads/{generateImageSizeFilename.js → generateFileData/utils/generateImageSizeFilename.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../../../src/auth/baseFields/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AAE9D,eAAO,MAAM,mBAAmB,EAAE,
|
|
1
|
+
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../../../src/auth/baseFields/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AAE9D,eAAO,MAAM,mBAAmB,EAAE,UAiDjC,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/baseFields/sessions.ts"],"sourcesContent":["import type { ArrayField } from '../../fields/config/types.js'\n\nexport const sessionsFieldConfig: ArrayField = {\n name: 'sessions',\n type: 'array',\n access: {\n read: ({ doc, req: { user } }) => {\n return user?.id === doc?.id\n },\n update: () => false,\n },\n admin: {\n disabled: true,\n },\n fields: [\n {\n name: 'id',\n type: 'text',\n required: true,\n },\n {\n name: 'createdAt',\n type: 'date',\n defaultValue: () => new Date(),\n },\n {\n name: 'expiresAt',\n type: 'date',\n required: true,\n },\n {\n name: 'refreshCount',\n type: 'number',\n },\n {\n name: 'refreshedAt',\n type: 'date',\n },\n ],\n}\n"],"names":["sessionsFieldConfig","name","type","access","read","doc","req","user","id","update","admin","disabled","fields","required","defaultValue","Date"],"mappings":"AAEA,OAAO,MAAMA,sBAAkC;IAC7CC,MAAM;IACNC,MAAM;IACNC,QAAQ;QACNC,MAAM,CAAC,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAE,EAAE;YAC3B,OAAOA,MAAMC,OAAOH,KAAKG;QAC3B;QACAC,QAAQ,IAAM;IAChB;IACAC,OAAO;QACLC,UAAU;IACZ;IACAC,QAAQ;QACN;YACEX,MAAM;YACNC,MAAM;YACNW,UAAU;QACZ;QACA;YACEZ,MAAM;YACNC,MAAM;YACNY,cAAc,IAAM,IAAIC;QAC1B;QACA;YACEd,MAAM;YACNC,MAAM;YACNW,UAAU;QACZ;QACA;YACEZ,MAAM;YACNC,MAAM;QACR;QACA;YACED,MAAM;YACNC,MAAM;QACR;KACD;AACH,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/baseFields/sessions.ts"],"sourcesContent":["import type { ArrayField } from '../../fields/config/types.js'\n\nexport const sessionsFieldConfig: ArrayField = {\n name: 'sessions',\n type: 'array',\n access: {\n read: ({ doc, req: { user } }) => {\n return user?.id === doc?.id\n },\n update: () => false,\n },\n admin: {\n disabled: true,\n },\n fields: [\n {\n name: 'id',\n type: 'text',\n required: true,\n },\n {\n name: 'createdAt',\n type: 'date',\n defaultValue: () => new Date(),\n },\n {\n name: 'expiresAt',\n type: 'date',\n required: true,\n },\n {\n name: 'refreshCount',\n type: 'number',\n },\n {\n name: 'refreshedAt',\n type: 'date',\n },\n {\n name: 'label',\n type: 'text',\n },\n {\n name: 'type',\n type: 'text',\n },\n {\n name: 'metadata',\n type: 'json',\n },\n ],\n}\n"],"names":["sessionsFieldConfig","name","type","access","read","doc","req","user","id","update","admin","disabled","fields","required","defaultValue","Date"],"mappings":"AAEA,OAAO,MAAMA,sBAAkC;IAC7CC,MAAM;IACNC,MAAM;IACNC,QAAQ;QACNC,MAAM,CAAC,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAE,EAAE;YAC3B,OAAOA,MAAMC,OAAOH,KAAKG;QAC3B;QACAC,QAAQ,IAAM;IAChB;IACAC,OAAO;QACLC,UAAU;IACZ;IACAC,QAAQ;QACN;YACEX,MAAM;YACNC,MAAM;YACNW,UAAU;QACZ;QACA;YACEZ,MAAM;YACNC,MAAM;YACNY,cAAc,IAAM,IAAIC;QAC1B;QACA;YACEd,MAAM;YACNC,MAAM;YACNW,UAAU;QACZ;QACA;YACEZ,MAAM;YACNC,MAAM;QACR;QACA;YACED,MAAM;YACNC,MAAM;QACR;QACA;YACED,MAAM;YACNC,MAAM;QACR;QACA;YACED,MAAM;YACNC,MAAM;QACR;QACA;YACED,MAAM;YACNC,MAAM;QACR;KACD;AACH,EAAC"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { SanitizedCollectionConfig } from '../collections/config/types.js';
|
|
2
|
-
import type { AuthenticatedUser } from '../index.js';
|
|
2
|
+
import type { AuthenticatedUser, UserSession } from '../index.js';
|
|
3
3
|
import type { PayloadRequest } from '../types/index.js';
|
|
4
4
|
/**
|
|
5
5
|
* Starts a login session for the user and signs the JWT for it, the same token a password login
|
|
6
6
|
* returns. Payload's JWT strategy accepts it. The session is saved on the user right away.
|
|
7
7
|
*/
|
|
8
|
-
export declare const createAuthToken: ({ collectionConfig, email, req, shouldCreateRefreshToken, user, }: {
|
|
8
|
+
export declare const createAuthToken: ({ type, collectionConfig, email, label, metadata, req, shouldCreateRefreshToken, user, }: {
|
|
9
9
|
collectionConfig: SanitizedCollectionConfig;
|
|
10
10
|
/** The `email` claim of the token. */
|
|
11
11
|
email: string;
|
|
@@ -17,7 +17,7 @@ export declare const createAuthToken: ({ collectionConfig, email, req, shouldCre
|
|
|
17
17
|
*/
|
|
18
18
|
shouldCreateRefreshToken?: boolean;
|
|
19
19
|
user: AuthenticatedUser;
|
|
20
|
-
}) => Promise<{
|
|
20
|
+
} & Pick<UserSession, 'label' | 'metadata' | 'type'>) => Promise<{
|
|
21
21
|
exp: number;
|
|
22
22
|
refreshToken?: string;
|
|
23
23
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAuthToken.d.ts","sourceRoot":"","sources":["../../src/auth/createAuthToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"createAuthToken.d.ts","sourceRoot":"","sources":["../../src/auth/createAuthToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAOvD;;;GAGG;AACH,eAAO,MAAM,eAAe,6FASzB;IACD,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,sCAAsC;IACtC,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,cAAc,CAAA;IACnB;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAA;IAClC,IAAI,EAAE,iBAAiB,CAAA;CACxB,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,GAAG,UAAU,GAAG,MAAM,CAAC,KAAG,OAAO,CAAC;IAC7D,GAAG,EAAE,MAAM,CAAA;IACX,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;CACd,CA6BA,CAAA"}
|
|
@@ -5,9 +5,12 @@ import { addSessionToUser } from './sessions.js';
|
|
|
5
5
|
/**
|
|
6
6
|
* Starts a login session for the user and signs the JWT for it, the same token a password login
|
|
7
7
|
* returns. Payload's JWT strategy accepts it. The session is saved on the user right away.
|
|
8
|
-
*/ export const createAuthToken = async ({ collectionConfig, email, req, shouldCreateRefreshToken = false, user })=>{
|
|
8
|
+
*/ export const createAuthToken = async ({ type, collectionConfig, email, label, metadata, req, shouldCreateRefreshToken = false, user })=>{
|
|
9
9
|
const { session, sid } = await addSessionToUser({
|
|
10
|
+
type,
|
|
10
11
|
collectionConfig,
|
|
12
|
+
label,
|
|
13
|
+
metadata,
|
|
11
14
|
payload: req.payload,
|
|
12
15
|
req,
|
|
13
16
|
sessionExpiration: shouldCreateRefreshToken ? getRefreshTokenExpiration(collectionConfig) : undefined,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/createAuthToken.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { getFieldsToSign } from './getFieldsToSign.js'\nimport { jwtSign } from './jwt.js'\nimport { createRefreshToken, getRefreshTokenExpiration } from './redeemRefreshToken.js'\nimport { addSessionToUser } from './sessions.js'\n\n/**\n * Starts a login session for the user and signs the JWT for it, the same token a password login\n * returns. Payload's JWT strategy accepts it. The session is saved on the user right away.\n */\nexport const createAuthToken = async ({\n collectionConfig,\n email,\n req,\n shouldCreateRefreshToken = false,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n /** The `email` claim of the token. */\n email: string\n req: PayloadRequest\n /**\n * Also return a refresh token for the session, which `redeemRefreshToken` trades for a new token.\n * The session then lasts `auth.refreshTokens.expiration` from each refresh, or 30 days when the\n * collection doesn't enable refresh tokens. Requires `auth.useSessions`.\n */\n shouldCreateRefreshToken?: boolean\n user: AuthenticatedUser\n}): Promise<{\n exp: number\n refreshToken?: string\n /**\n * The ID of the session the token belongs to. Removing that session from the user, like logout\n * does, makes the token stop working.\n */\n sid?: string\n token: string\n}> => {\n const { session, sid } = await addSessionToUser({\n collectionConfig,\n payload: req.payload,\n req,\n sessionExpiration: shouldCreateRefreshToken\n ? getRefreshTokenExpiration(collectionConfig)\n : undefined,\n user,\n })\n\n const { exp, token } = await jwtSign({\n fieldsToSign: getFieldsToSign({ collectionConfig, email, sid, user }),\n secret: req.payload.secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n return {\n exp,\n refreshToken:\n shouldCreateRefreshToken && session\n ? createRefreshToken({ collectionConfig, req, session, userID: user.id })\n : undefined,\n sid,\n token,\n }\n}\n"],"names":["getFieldsToSign","jwtSign","createRefreshToken","getRefreshTokenExpiration","addSessionToUser","createAuthToken","collectionConfig","email","req","shouldCreateRefreshToken","user","session","sid","payload","sessionExpiration","undefined","exp","token","fieldsToSign","secret","tokenExpiration","auth","refreshToken","userID","id"],"mappings":"AAIA,SAASA,eAAe,QAAQ,uBAAsB;AACtD,SAASC,OAAO,QAAQ,WAAU;AAClC,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,0BAAyB;AACvF,SAASC,gBAAgB,QAAQ,gBAAe;AAEhD;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,OAAO,EACpCC,gBAAgB,EAChBC,KAAK,EACLC,GAAG,EACHC,2BAA2B,KAAK,EAChCC,IAAI,
|
|
1
|
+
{"version":3,"sources":["../../src/auth/createAuthToken.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, UserSession } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { getFieldsToSign } from './getFieldsToSign.js'\nimport { jwtSign } from './jwt.js'\nimport { createRefreshToken, getRefreshTokenExpiration } from './redeemRefreshToken.js'\nimport { addSessionToUser } from './sessions.js'\n\n/**\n * Starts a login session for the user and signs the JWT for it, the same token a password login\n * returns. Payload's JWT strategy accepts it. The session is saved on the user right away.\n */\nexport const createAuthToken = async ({\n type,\n collectionConfig,\n email,\n label,\n metadata,\n req,\n shouldCreateRefreshToken = false,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n /** The `email` claim of the token. */\n email: string\n req: PayloadRequest\n /**\n * Also return a refresh token for the session, which `redeemRefreshToken` trades for a new token.\n * The session then lasts `auth.refreshTokens.expiration` from each refresh, or 30 days when the\n * collection doesn't enable refresh tokens. Requires `auth.useSessions`.\n */\n shouldCreateRefreshToken?: boolean\n user: AuthenticatedUser\n} & Pick<UserSession, 'label' | 'metadata' | 'type'>): Promise<{\n exp: number\n refreshToken?: string\n /**\n * The ID of the session the token belongs to. Removing that session from the user, like logout\n * does, makes the token stop working.\n */\n sid?: string\n token: string\n}> => {\n const { session, sid } = await addSessionToUser({\n type,\n collectionConfig,\n label,\n metadata,\n payload: req.payload,\n req,\n sessionExpiration: shouldCreateRefreshToken\n ? getRefreshTokenExpiration(collectionConfig)\n : undefined,\n user,\n })\n\n const { exp, token } = await jwtSign({\n fieldsToSign: getFieldsToSign({ collectionConfig, email, sid, user }),\n secret: req.payload.secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n return {\n exp,\n refreshToken:\n shouldCreateRefreshToken && session\n ? createRefreshToken({ collectionConfig, req, session, userID: user.id })\n : undefined,\n sid,\n token,\n }\n}\n"],"names":["getFieldsToSign","jwtSign","createRefreshToken","getRefreshTokenExpiration","addSessionToUser","createAuthToken","type","collectionConfig","email","label","metadata","req","shouldCreateRefreshToken","user","session","sid","payload","sessionExpiration","undefined","exp","token","fieldsToSign","secret","tokenExpiration","auth","refreshToken","userID","id"],"mappings":"AAIA,SAASA,eAAe,QAAQ,uBAAsB;AACtD,SAASC,OAAO,QAAQ,WAAU;AAClC,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,0BAAyB;AACvF,SAASC,gBAAgB,QAAQ,gBAAe;AAEhD;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,OAAO,EACpCC,IAAI,EACJC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,QAAQ,EACRC,GAAG,EACHC,2BAA2B,KAAK,EAChCC,IAAI,EAa8C;IAUlD,MAAM,EAAEC,OAAO,EAAEC,GAAG,EAAE,GAAG,MAAMX,iBAAiB;QAC9CE;QACAC;QACAE;QACAC;QACAM,SAASL,IAAIK,OAAO;QACpBL;QACAM,mBAAmBL,2BACfT,0BAA0BI,oBAC1BW;QACJL;IACF;IAEA,MAAM,EAAEM,GAAG,EAAEC,KAAK,EAAE,GAAG,MAAMnB,QAAQ;QACnCoB,cAAcrB,gBAAgB;YAAEO;YAAkBC;YAAOO;YAAKF;QAAK;QACnES,QAAQX,IAAIK,OAAO,CAACM,MAAM;QAC1BC,iBAAiBhB,iBAAiBiB,IAAI,CAACD,eAAe;IACxD;IAEA,OAAO;QACLJ;QACAM,cACEb,4BAA4BE,UACxBZ,mBAAmB;YAAEK;YAAkBI;YAAKG;YAASY,QAAQb,KAAKc,EAAE;QAAC,KACrET;QACNH;QACAK;IACF;AACF,EAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A label for a session from the browser that started it, e.g. "Chrome on macOS". `undefined`
|
|
3
|
+
* when the User-Agent doesn't name a known browser or operating system, e.g. for scripts.
|
|
4
|
+
*/
|
|
5
|
+
export declare const getUserAgentLabel: ({ userAgent, }: {
|
|
6
|
+
userAgent: null | string | undefined;
|
|
7
|
+
}) => string | undefined;
|
|
8
|
+
//# sourceMappingURL=getUserAgentLabel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getUserAgentLabel.d.ts","sourceRoot":"","sources":["../../src/auth/getUserAgentLabel.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AACH,eAAO,MAAM,iBAAiB,mBAE3B;IACD,SAAS,EAAE,IAAI,GAAG,MAAM,GAAG,SAAS,CAAA;CACrC,KAAG,MAAM,GAAG,SAaZ,CAAA"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Checked in order: each browser's User-Agent also names the ones it's based on
|
|
2
|
+
const browsers = [
|
|
3
|
+
[
|
|
4
|
+
'Edge',
|
|
5
|
+
/Edg(?:e|A|iOS)?\//
|
|
6
|
+
],
|
|
7
|
+
[
|
|
8
|
+
'Opera',
|
|
9
|
+
/OPR\/|Opera/
|
|
10
|
+
],
|
|
11
|
+
[
|
|
12
|
+
'Samsung Internet',
|
|
13
|
+
/SamsungBrowser\//
|
|
14
|
+
],
|
|
15
|
+
[
|
|
16
|
+
'Firefox',
|
|
17
|
+
/Firefox\/|FxiOS\//
|
|
18
|
+
],
|
|
19
|
+
[
|
|
20
|
+
'Chrome',
|
|
21
|
+
/Chrome\/|CriOS\//
|
|
22
|
+
],
|
|
23
|
+
[
|
|
24
|
+
'Safari',
|
|
25
|
+
/Safari\//
|
|
26
|
+
]
|
|
27
|
+
];
|
|
28
|
+
// Android before Linux, since Android's User-Agent mentions Linux too
|
|
29
|
+
const operatingSystems = [
|
|
30
|
+
[
|
|
31
|
+
'iOS',
|
|
32
|
+
/iPhone|iPad|iPod/
|
|
33
|
+
],
|
|
34
|
+
[
|
|
35
|
+
'Android',
|
|
36
|
+
/Android/
|
|
37
|
+
],
|
|
38
|
+
[
|
|
39
|
+
'ChromeOS',
|
|
40
|
+
/CrOS/
|
|
41
|
+
],
|
|
42
|
+
[
|
|
43
|
+
'macOS',
|
|
44
|
+
/Macintosh|Mac OS X/
|
|
45
|
+
],
|
|
46
|
+
[
|
|
47
|
+
'Windows',
|
|
48
|
+
/Windows/
|
|
49
|
+
],
|
|
50
|
+
[
|
|
51
|
+
'Linux',
|
|
52
|
+
/Linux/
|
|
53
|
+
]
|
|
54
|
+
];
|
|
55
|
+
/**
|
|
56
|
+
* A label for a session from the browser that started it, e.g. "Chrome on macOS". `undefined`
|
|
57
|
+
* when the User-Agent doesn't name a known browser or operating system, e.g. for scripts.
|
|
58
|
+
*/ export const getUserAgentLabel = ({ userAgent })=>{
|
|
59
|
+
if (!userAgent) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const browser = browsers.find(([, pattern])=>pattern.test(userAgent))?.[0];
|
|
63
|
+
const operatingSystem = operatingSystems.find(([, pattern])=>pattern.test(userAgent))?.[0];
|
|
64
|
+
if (browser && operatingSystem) {
|
|
65
|
+
return `${browser} on ${operatingSystem}`;
|
|
66
|
+
}
|
|
67
|
+
return browser ?? operatingSystem;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=getUserAgentLabel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/getUserAgentLabel.ts"],"sourcesContent":["// Checked in order: each browser's User-Agent also names the ones it's based on\nconst browsers: [name: string, pattern: RegExp][] = [\n ['Edge', /Edg(?:e|A|iOS)?\\//],\n ['Opera', /OPR\\/|Opera/],\n ['Samsung Internet', /SamsungBrowser\\//],\n ['Firefox', /Firefox\\/|FxiOS\\//],\n ['Chrome', /Chrome\\/|CriOS\\//],\n ['Safari', /Safari\\//],\n]\n\n// Android before Linux, since Android's User-Agent mentions Linux too\nconst operatingSystems: [name: string, pattern: RegExp][] = [\n ['iOS', /iPhone|iPad|iPod/],\n ['Android', /Android/],\n ['ChromeOS', /CrOS/],\n ['macOS', /Macintosh|Mac OS X/],\n ['Windows', /Windows/],\n ['Linux', /Linux/],\n]\n\n/**\n * A label for a session from the browser that started it, e.g. \"Chrome on macOS\". `undefined`\n * when the User-Agent doesn't name a known browser or operating system, e.g. for scripts.\n */\nexport const getUserAgentLabel = ({\n userAgent,\n}: {\n userAgent: null | string | undefined\n}): string | undefined => {\n if (!userAgent) {\n return undefined\n }\n\n const browser = browsers.find(([, pattern]) => pattern.test(userAgent))?.[0]\n const operatingSystem = operatingSystems.find(([, pattern]) => pattern.test(userAgent))?.[0]\n\n if (browser && operatingSystem) {\n return `${browser} on ${operatingSystem}`\n }\n\n return browser ?? operatingSystem\n}\n"],"names":["browsers","operatingSystems","getUserAgentLabel","userAgent","undefined","browser","find","pattern","test","operatingSystem"],"mappings":"AAAA,gFAAgF;AAChF,MAAMA,WAA8C;IAClD;QAAC;QAAQ;KAAoB;IAC7B;QAAC;QAAS;KAAc;IACxB;QAAC;QAAoB;KAAmB;IACxC;QAAC;QAAW;KAAoB;IAChC;QAAC;QAAU;KAAmB;IAC9B;QAAC;QAAU;KAAW;CACvB;AAED,sEAAsE;AACtE,MAAMC,mBAAsD;IAC1D;QAAC;QAAO;KAAmB;IAC3B;QAAC;QAAW;KAAU;IACtB;QAAC;QAAY;KAAO;IACpB;QAAC;QAAS;KAAqB;IAC/B;QAAC;QAAW;KAAU;IACtB;QAAC;QAAS;KAAQ;CACnB;AAED;;;CAGC,GACD,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,SAAS,EAGV;IACC,IAAI,CAACA,WAAW;QACd,OAAOC;IACT;IAEA,MAAMC,UAAUL,SAASM,IAAI,CAAC,CAAC,GAAGC,QAAQ,GAAKA,QAAQC,IAAI,CAACL,aAAa,CAAC,EAAE;IAC5E,MAAMM,kBAAkBR,iBAAiBK,IAAI,CAAC,CAAC,GAAGC,QAAQ,GAAKA,QAAQC,IAAI,CAACL,aAAa,CAAC,EAAE;IAE5F,IAAIE,WAAWI,iBAAiB;QAC9B,OAAO,GAAGJ,QAAQ,IAAI,EAAEI,iBAAiB;IAC3C;IAEA,OAAOJ,WAAWI;AACpB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
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,kBAAkB,EAA2B,MAAM,gBAAgB,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AACjE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;
|
|
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,kBAAkB,EAA2B,MAAM,gBAAgB,CAAA;AACjF,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AACjE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AA0BpD,MAAM,MAAM,WAAW,CAAC,KAAK,SAAS,kBAAkB,IAAI;IAC1D,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,gFAAgF;IAChF,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,iBAAiB,GAAG,sBAAsB,CAAC,KAAK,CAAC,CAAA;CACzD,CAAA;AAED,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,kBAAkB,IAAI;IACxD,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,CAAC,KAAK,SAAS,kBAAkB,IAAI;IAChE,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAA;CACpC,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,SAAS,kBAAkB,yCAIlE,wBAAwB,CAAC,KAAK,CAAC,SAQjC,CAAA;AAED,eAAO,MAAM,cAAc,GAAU,KAAK,SAAS,kBAAkB,gBACrD,SAAS,CAAC,KAAK,CAAC,KAC7B,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CA8V5B,CAAA"}
|
|
@@ -9,6 +9,7 @@ import { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.j
|
|
|
9
9
|
import { applyUserReadAccess } from '../applyUserReadAccess.js';
|
|
10
10
|
import { createAuthToken } from '../createAuthToken.js';
|
|
11
11
|
import { getLoginOptions } from '../getLoginOptions.js';
|
|
12
|
+
import { getUserAgentLabel } from '../getUserAgentLabel.js';
|
|
12
13
|
import { isUserLocked } from '../isUserLocked.js';
|
|
13
14
|
import { revokeSession } from '../sessions.js';
|
|
14
15
|
import { authenticateLocalStrategy } from '../strategies/local/authenticate.js';
|
|
@@ -220,8 +221,12 @@ export const loginOperation = async (incomingArgs)=>{
|
|
|
220
221
|
});
|
|
221
222
|
}
|
|
222
223
|
const { exp, refreshToken, token, ...session } = await createAuthToken({
|
|
224
|
+
type: 'login',
|
|
223
225
|
collectionConfig,
|
|
224
226
|
email: sanitizedEmail,
|
|
227
|
+
label: getUserAgentLabel({
|
|
228
|
+
userAgent: req.headers?.get('User-Agent')
|
|
229
|
+
}),
|
|
225
230
|
req,
|
|
226
231
|
shouldCreateRefreshToken: Boolean(collectionConfig.auth.refreshTokens),
|
|
227
232
|
user
|
|
@@ -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 { AuthCollectionSlug, AuthenticatedUser, User } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\nimport type { AuthRuntimeFields } from '../types.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 { commitTransaction, Forbidden, initTransaction } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { createAuthToken } from '../createAuthToken.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type LoginResult<TSlug extends AuthCollectionSlug> = {\n exp?: number\n /** With `auth.refreshTokens`, trades for a new token after this one expires. */\n refreshToken?: string\n token?: string\n user?: AuthRuntimeFields & DataFromCollectionSlug<TSlug>\n}\n\nexport type Arguments<TSlug extends AuthCollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs<TSlug extends AuthCollectionSlug> = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: DataFromCollectionSlug<TSlug>\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 = <TSlug extends AuthCollectionSlug>({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs<TSlug>) => {\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 AuthCollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<LoginResult<TSlug>> => {\n let args = incomingArgs\n\n assertNoValidationWrite(args.req)\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req,\n req: { payload },\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<User>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as AuthenticatedUser\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 authenticatedHash = user.hash\n const authenticatedSalt = user.salt\n const authResult = await authenticateLocalStrategy({\n doc: user,\n password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\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 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 // Authentication successful - start transaction for remaining operations\n const shouldCommit = await initTransaction(args.req)\n let sid: string | undefined\n\n try {\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<User>({\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 { exp, refreshToken, token, ...session } = await createAuthToken({\n collectionConfig,\n email: sanitizedEmail!,\n req,\n shouldCreateRefreshToken: Boolean(collectionConfig.auth.refreshTokens),\n user,\n })\n sid = session.sid\n\n if (\n authResult.shouldUpdatePasswordHash &&\n typeof authenticatedHash === 'string' &&\n typeof authenticatedSalt === 'string'\n ) {\n try {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n isPasswordAuthenticated: true,\n password,\n req,\n })\n\n await payload.db.updateOne({\n collection: collectionConfig.slug,\n data: { hash, salt },\n req,\n select: { id: true },\n where: {\n id: { equals: user.id },\n hash: { equals: authenticatedHash },\n salt: { equals: authenticatedSalt },\n },\n })\n } catch (err) {\n // Rehashing is opportunistic and is retried on the next login, so a failure here\n // must not reject an otherwise valid login or discard the session already created\n payload.logger.error({ err, msg: 'Failed to update the stored password hash' })\n }\n }\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 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 const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: showHiddenFields!,\n user,\n })\n\n let result: LoginResult<TSlug> = {\n exp,\n refreshToken,\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n // The password was right, but the login failed afterwards, e.g. in a `beforeLogin` hook, so\n // remove the session it started\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n })\n }\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","commitTransaction","Forbidden","initTransaction","appendNonTrashedFilter","assertNoValidationWrite","killTransaction","sanitizeInternalFields","applyUserReadAccess","createAuthToken","getLoginOptions","isUserLocked","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","operation","overrideAccess","collectionConfig","data","depth","payload","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","authenticatedHash","hash","authenticatedSalt","salt","authResult","doc","passwordHashIterations","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","shouldCommit","sid","loginAttempts","select","id","exp","refreshToken","token","session","shouldCreateRefreshToken","refreshTokens","shouldUpdatePasswordHash","isPasswordAuthenticated","updateOne","err","logger","error","msg","hooks","beforeLogin","length","hook","context","afterLogin","userWithReadAccess","result"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SACEC,mBAAmB,EACn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gBAClBsB;gBACAG;gBACAlB;gBACA2D;gBACA1D;YACF;QACF;QACA,MAAMd,gBAAgBqB,KAAKR,GAAG;QAC9B,MAAM0E;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 { AuthCollectionSlug, AuthenticatedUser, User } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\nimport type { AuthRuntimeFields } from '../types.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 { commitTransaction, Forbidden, initTransaction } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { createAuthToken } from '../createAuthToken.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { getUserAgentLabel } from '../getUserAgentLabel.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type LoginResult<TSlug extends AuthCollectionSlug> = {\n exp?: number\n /** With `auth.refreshTokens`, trades for a new token after this one expires. */\n refreshToken?: string\n token?: string\n user?: AuthRuntimeFields & DataFromCollectionSlug<TSlug>\n}\n\nexport type Arguments<TSlug extends AuthCollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs<TSlug extends AuthCollectionSlug> = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: DataFromCollectionSlug<TSlug>\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 = <TSlug extends AuthCollectionSlug>({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs<TSlug>) => {\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 AuthCollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<LoginResult<TSlug>> => {\n let args = incomingArgs\n\n assertNoValidationWrite(args.req)\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req,\n req: { payload },\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<User>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as AuthenticatedUser\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 authenticatedHash = user.hash\n const authenticatedSalt = user.salt\n const authResult = await authenticateLocalStrategy({\n doc: user,\n password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\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 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 // Authentication successful - start transaction for remaining operations\n const shouldCommit = await initTransaction(args.req)\n let sid: string | undefined\n\n try {\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<User>({\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 { exp, refreshToken, token, ...session } = await createAuthToken({\n type: 'login',\n collectionConfig,\n email: sanitizedEmail!,\n label: getUserAgentLabel({ userAgent: req.headers?.get('User-Agent') }),\n req,\n shouldCreateRefreshToken: Boolean(collectionConfig.auth.refreshTokens),\n user,\n })\n sid = session.sid\n\n if (\n authResult.shouldUpdatePasswordHash &&\n typeof authenticatedHash === 'string' &&\n typeof authenticatedSalt === 'string'\n ) {\n try {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n isPasswordAuthenticated: true,\n password,\n req,\n })\n\n await payload.db.updateOne({\n collection: collectionConfig.slug,\n data: { hash, salt },\n req,\n select: { id: true },\n where: {\n id: { equals: user.id },\n hash: { equals: authenticatedHash },\n salt: { equals: authenticatedSalt },\n },\n })\n } catch (err) {\n // Rehashing is opportunistic and is retried on the next login, so a failure here\n // must not reject an otherwise valid login or discard the session already created\n payload.logger.error({ err, msg: 'Failed to update the stored password hash' })\n }\n }\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 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 const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: showHiddenFields!,\n user,\n })\n\n let result: LoginResult<TSlug> = {\n exp,\n refreshToken,\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n // The password was right, but the login failed afterwards, e.g. in a `beforeLogin` hook, so\n // remove the session it started\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n })\n }\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","commitTransaction","Forbidden","initTransaction","appendNonTrashedFilter","assertNoValidationWrite","killTransaction","sanitizeInternalFields","applyUserReadAccess","createAuthToken","getLoginOptions","getUserAgentLabel","isUserLocked","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","operation","overrideAccess","collectionConfig","data","depth","payload","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","authenticatedHash","hash","authenticatedSalt","salt","authResult","doc","passwordHashIterations","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","shouldCommit","sid","loginAttempts","select","id","exp","refreshToken","token","session","type","label","userAgent","headers","get","shouldCreateRefreshToken","refreshTokens","shouldUpdatePasswordHash","isPasswordAuthenticated","updateOne","err","logger","error","msg","hooks","beforeLogin","length","hook","context","afterLogin","userWithReadAccess","result"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SACEC,mBAAmB,EACnBC,UAAU,EACVC,eAAe,EACfC,eAAe,QACV,wBAAuB;AAC9B,SAASC,iBAAiB,EAAEC,SAAS,EAAEC,eAAe,QAAQ,iBAAgB;AAC9E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAAS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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAGX,MAAM,mCAAmC,CAAA;AAE1C,OAAO,KAAK,EAAE,kBAAkB,EAAqB,MAAM,gBAAgB,CAAA;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAGX,MAAM,mCAAmC,CAAA;AAE1C,OAAO,KAAK,EAAE,kBAAkB,EAAqB,MAAM,gBAAgB,CAAA;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAkB1D,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,kBAAkB,QACrE,SAAS,KACd,OAAO,CAAC,MAAM,CAoOhB,CAAA"}
|
|
@@ -9,6 +9,7 @@ import { initTransaction } from '../../utilities/initTransaction.js';
|
|
|
9
9
|
import { killTransaction } from '../../utilities/killTransaction.js';
|
|
10
10
|
import { applyUserReadAccess } from '../applyUserReadAccess.js';
|
|
11
11
|
import { createAuthToken } from '../createAuthToken.js';
|
|
12
|
+
import { getUserAgentLabel } from '../getUserAgentLabel.js';
|
|
12
13
|
import { revokeSession } from '../sessions.js';
|
|
13
14
|
import { authenticateLocalStrategy } from '../strategies/local/authenticate.js';
|
|
14
15
|
import { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js';
|
|
@@ -114,8 +115,12 @@ export const resetPasswordOperation = async (args)=>{
|
|
|
114
115
|
user.collection = collectionConfig.slug;
|
|
115
116
|
user._strategy = 'local-jwt';
|
|
116
117
|
const { token, ...session } = await createAuthToken({
|
|
118
|
+
type: 'login',
|
|
117
119
|
collectionConfig,
|
|
118
120
|
email: user.email,
|
|
121
|
+
label: getUserAgentLabel({
|
|
122
|
+
userAgent: req.headers?.get('User-Agent')
|
|
123
|
+
}),
|
|
119
124
|
req,
|
|
120
125
|
user
|
|
121
126
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import type {\n Collection,\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n} from '../../collections/config/types.js'\nimport type { Validate } from '../../fields/config/types.js'\nimport type { AuthCollectionSlug, AuthenticatedUser } 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, ValidationError } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { createAuthToken } from '../createAuthToken.js'\nimport { revokeSession } 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 AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: { payload },\n req,\n } = args\n\n assertNoValidationWrite(req)\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 let sid: string | undefined\n let sessionUser: AuthenticatedUser | null = null\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 overrideAccess,\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 let user = await payload.db.findOne<AuthenticatedUser>({\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 await validatePasswordField({\n collectionConfig,\n overrideAccess,\n password: data.password,\n req,\n user,\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.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\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 if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\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({\n doc,\n password: data.password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\n\n user = doc as AuthenticatedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const { token, ...session } = await createAuthToken({\n collectionConfig,\n email: user.email!,\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\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 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 user!.collection = collectionConfig.slug\n user!._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user: user!,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n // Logging in with the new password failed, e.g. in a `beforeLogin` hook, so remove the session\n // it started\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n\n/**\n * Runs the `password` field override's validation, which `payload.db.updateOne` skips.\n */\nasync function validatePasswordField({\n collectionConfig,\n overrideAccess,\n password,\n req,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n overrideAccess: boolean\n password: string\n req: PayloadRequest\n user: AuthenticatedUser\n}): Promise<void> {\n const passwordField = collectionConfig.flattenedFields.find((field) => field.name === 'password')\n\n if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {\n return\n }\n\n const validate = passwordField.validate as Validate<string>\n const dataToValidate = { ...user, password }\n\n const validationResult = await validate(password, {\n ...passwordField,\n id: user.id,\n blockData: {},\n collectionSlug: collectionConfig.slug,\n data: dataToValidate,\n event: 'submit',\n operation: 'update',\n overrideAccess,\n path: ['password'],\n preferences: { fields: {} },\n req,\n siblingData: dataToValidate,\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","APIError","Forbidden","ValidationError","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","httpStatus","initTransaction","killTransaction","applyUserReadAccess","createAuthToken","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","validatePasswordField","password","hash","salt","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","passwordHashIterations","_strategy","session","email","beforeLogin","afterLogin","userWithReadAccess","showHiddenFields","result","error","passwordField","flattenedFields","find","field","name","validate","dataToValidate","validationResult","blockData","collectionSlug","event","path","preferences","fields","siblingData","errors","message"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,EAAEC,eAAe,QAAQ,wBAAuB;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,UAAU,QAAQ,gCAA+B;AAC1D,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,aAAa,QAAQ,iBAAgB;AAC9C,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,iBAAiB,KAAK,EACtBC,KAAK,EAAEC,OAAO,EAAE,EAChBD,GAAG,EACJ,GAAGP;IAEJX,wBAAwBkB;IAExB,IACE,CAACE,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACR,MAAM,YAC5C,CAACK,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACR,MAAM,aAC5C;QACA,MAAM,IAAInB,SAAS,0BAA0BM,W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QACF;QACA,MAAMzB,gBAAgBc;QACtB,MAAM2D;IACR;AACF,EAAC;AAED;;CAEC,GACD,eAAe7B,sBAAsB,EACnClC,gBAAgB,EAChBG,cAAc,EACdgC,QAAQ,EACR/B,GAAG,EACHyB,IAAI,EAOL;IACC,MAAMmC,gBAAgBhE,iBAAiBiE,eAAe,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAK;IAEtF,IAAI,CAACJ,iBAAiB,CAAE,CAAA,cAAcA,aAAY,KAAM,CAACA,cAAcK,QAAQ,EAAE;QAC/E;IACF;IAEA,MAAMA,WAAWL,cAAcK,QAAQ;IACvC,MAAMC,iBAAiB;QAAE,GAAGzC,IAAI;QAAEM;IAAS;IAE3C,MAAMoC,mBAAmB,MAAMF,SAASlC,UAAU;QAChD,GAAG6B,aAAa;QAChBX,IAAIxB,KAAKwB,EAAE;QACXmB,WAAW,CAAC;QACZC,gBAAgBzE,iBAAiBgC,IAAI;QACrC/B,MAAMqE;QACNI,OAAO;QACPzD,WAAW;QACXd;QACAwE,MAAM;YAAC;SAAW;QAClBC,aAAa;YAAEC,QAAQ,CAAC;QAAE;QAC1BzE;QACA0E,aAAaR;IACf;IAEA,IAAI,OAAOC,qBAAqB,UAAU;QACxC,MAAM,IAAIvF,gBAAgB;YACxBc,YAAYE,iBAAiBgC,IAAI;YACjC+C,QAAQ;gBAAC;oBAAEC,SAAST;oBAAkBI,MAAM;gBAAW;aAAE;QAC3D;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import type {\n Collection,\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n} from '../../collections/config/types.js'\nimport type { Validate } from '../../fields/config/types.js'\nimport type { AuthCollectionSlug, AuthenticatedUser } 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, ValidationError } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { createAuthToken } from '../createAuthToken.js'\nimport { getUserAgentLabel } from '../getUserAgentLabel.js'\nimport { revokeSession } 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 AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: { payload },\n req,\n } = args\n\n assertNoValidationWrite(req)\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 let sid: string | undefined\n let sessionUser: AuthenticatedUser | null = null\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 overrideAccess,\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 let user = await payload.db.findOne<AuthenticatedUser>({\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 await validatePasswordField({\n collectionConfig,\n overrideAccess,\n password: data.password,\n req,\n user,\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.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\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 if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\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({\n doc,\n password: data.password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\n\n user = doc as AuthenticatedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const { token, ...session } = await createAuthToken({\n type: 'login',\n collectionConfig,\n email: user.email!,\n label: getUserAgentLabel({ userAgent: req.headers?.get('User-Agent') }),\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\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 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 user!.collection = collectionConfig.slug\n user!._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user: user!,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n // Logging in with the new password failed, e.g. in a `beforeLogin` hook, so remove the session\n // it started\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n\n/**\n * Runs the `password` field override's validation, which `payload.db.updateOne` skips.\n */\nasync function validatePasswordField({\n collectionConfig,\n overrideAccess,\n password,\n req,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n overrideAccess: boolean\n password: string\n req: PayloadRequest\n user: AuthenticatedUser\n}): Promise<void> {\n const passwordField = collectionConfig.flattenedFields.find((field) => field.name === 'password')\n\n if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {\n return\n }\n\n const validate = passwordField.validate as Validate<string>\n const dataToValidate = { ...user, password }\n\n const validationResult = await validate(password, {\n ...passwordField,\n id: user.id,\n blockData: {},\n collectionSlug: collectionConfig.slug,\n data: dataToValidate,\n event: 'submit',\n operation: 'update',\n overrideAccess,\n path: ['password'],\n preferences: { fields: {} },\n req,\n siblingData: dataToValidate,\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","APIError","Forbidden","ValidationError","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","httpStatus","initTransaction","killTransaction","applyUserReadAccess","createAuthToken","getUserAgentLabel","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","validatePasswordField","password","hash","salt","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","passwordHashIterations","_strategy","session","type","email","label","userAgent","headers","get","beforeLogin","afterLogin","userWithReadAccess","showHiddenFields","result","error","passwordField","flattenedFields","find","field","name","validate","dataToValidate","validationResult","blockData","collectionSlug","event","path","preferences","fields","siblingData","errors","message"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,EAAEC,eAAe,QAAQ,wBAAuB;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,UAAU,QAAQ,gCAA+B;AAC1D,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,eAAe,QAAQ,wBAAu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,MAAM0E;QACNI,OAAO;QACP9D,WAAW;QACXd;QACA6E,MAAM;YAAC;SAAW;QAClBC,aAAa;YAAEC,QAAQ,CAAC;QAAE;QAC1B9E;QACA+E,aAAaR;IACf;IAEA,IAAI,OAAOC,qBAAqB,UAAU;QACxC,MAAM,IAAI7F,gBAAgB;YACxBe,YAAYE,iBAAiBgC,IAAI;YACjCoD,QAAQ;gBAAC;oBAAEC,SAAST;oBAAkBI,MAAM;gBAAW;aAAE;QAC3D;IACF;AACF"}
|
package/dist/auth/sessions.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export declare const removeExpiredSessions: (sessions: UserSession[]) => UserSes
|
|
|
9
9
|
* Adds a session to the user and removes expired sessions
|
|
10
10
|
* @returns The session and its ID (sid) if sessions are used
|
|
11
11
|
*/
|
|
12
|
-
export declare const addSessionToUser: ({ collectionConfig, payload, req, sessionExpiration, user, }: {
|
|
12
|
+
export declare const addSessionToUser: ({ type, collectionConfig, label, metadata, payload, req, sessionExpiration, user, }: {
|
|
13
13
|
collectionConfig: SanitizedCollectionConfig;
|
|
14
14
|
payload: Payload;
|
|
15
15
|
req: PayloadRequest;
|
|
@@ -20,7 +20,7 @@ export declare const addSessionToUser: ({ collectionConfig, payload, req, sessio
|
|
|
20
20
|
*/
|
|
21
21
|
sessionExpiration?: number;
|
|
22
22
|
user: AuthenticatedUser;
|
|
23
|
-
}) => Promise<{
|
|
23
|
+
} & Pick<UserSession, 'label' | 'metadata' | 'type'>) => Promise<{
|
|
24
24
|
session?: UserSession;
|
|
25
25
|
sid?: string;
|
|
26
26
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../../src/auth/sessions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACvE,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G,WAAW,CA6BlC,CAAA;AAED,eAAO,MAAM,aAAa,mDAMvB;IACD,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;CAClB,KAAG,OAAO,CAAC,IAAI,CAaf,CAAA"}
|
package/dist/auth/sessions.js
CHANGED
|
@@ -12,7 +12,7 @@ import { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js
|
|
|
12
12
|
/**
|
|
13
13
|
* Adds a session to the user and removes expired sessions
|
|
14
14
|
* @returns The session and its ID (sid) if sessions are used
|
|
15
|
-
*/ export const addSessionToUser = async ({ collectionConfig, payload, req, sessionExpiration = collectionConfig.auth.tokenExpiration, user })=>{
|
|
15
|
+
*/ export const addSessionToUser = async ({ type, collectionConfig, label, metadata, payload, req, sessionExpiration = collectionConfig.auth.tokenExpiration, user })=>{
|
|
16
16
|
assertNoValidationWrite(req);
|
|
17
17
|
let session;
|
|
18
18
|
let sid;
|
|
@@ -23,8 +23,11 @@ import { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js
|
|
|
23
23
|
const expiresAt = new Date(now.getTime() + sessionExpiration * 1000);
|
|
24
24
|
session = {
|
|
25
25
|
id: sid,
|
|
26
|
+
type,
|
|
26
27
|
createdAt: now,
|
|
27
|
-
expiresAt
|
|
28
|
+
expiresAt,
|
|
29
|
+
label,
|
|
30
|
+
metadata
|
|
28
31
|
};
|
|
29
32
|
if (!user.sessions?.length) {
|
|
30
33
|
user.sessions = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/sessions.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, User, UserSession } from '../index.js'\nimport type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js'\n\n/**\n * Removes expired sessions from an array of sessions\n */\nexport const removeExpiredSessions = (sessions: UserSession[]): UserSession[] => {\n const now = new Date()\n\n return sessions.filter(({ expiresAt }) => {\n const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt)\n return expiry > now\n })\n}\n\n/**\n * Adds a session to the user and removes expired sessions\n * @returns The session and its ID (sid) if sessions are used\n */\nexport const addSessionToUser = async ({\n collectionConfig,\n payload,\n req,\n sessionExpiration = collectionConfig.auth.tokenExpiration,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n /**\n * Seconds until the session expires.\n *\n * @default collectionConfig.auth.tokenExpiration\n */\n sessionExpiration?: number\n user: AuthenticatedUser\n}): Promise<{
|
|
1
|
+
{"version":3,"sources":["../../src/auth/sessions.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, User, UserSession } from '../index.js'\nimport type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js'\n\n/**\n * Removes expired sessions from an array of sessions\n */\nexport const removeExpiredSessions = (sessions: UserSession[]): UserSession[] => {\n const now = new Date()\n\n return sessions.filter(({ expiresAt }) => {\n const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt)\n return expiry > now\n })\n}\n\n/**\n * Adds a session to the user and removes expired sessions\n * @returns The session and its ID (sid) if sessions are used\n */\nexport const addSessionToUser = async ({\n type,\n collectionConfig,\n label,\n metadata,\n payload,\n req,\n sessionExpiration = collectionConfig.auth.tokenExpiration,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n /**\n * Seconds until the session expires.\n *\n * @default collectionConfig.auth.tokenExpiration\n */\n sessionExpiration?: number\n user: AuthenticatedUser\n} & Pick<UserSession, 'label' | 'metadata' | 'type'>): Promise<{\n session?: UserSession\n sid?: string\n}> => {\n assertNoValidationWrite(req)\n\n let session: undefined | UserSession\n let sid: string | undefined\n if (collectionConfig.auth.useSessions) {\n // Add session to user\n sid = uuid()\n const now = new Date()\n const expiresAt = new Date(now.getTime() + sessionExpiration * 1000)\n\n session = { id: sid, type, createdAt: now, expiresAt, label, metadata }\n\n if (!user.sessions?.length) {\n user.sessions = [session]\n } else {\n user.sessions = removeExpiredSessions(user.sessions)\n user.sessions.push(session)\n }\n\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n // Prevent updatedAt from being updated when only adding a session\n updatedAt: null,\n },\n req,\n returning: false,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n }\n\n return {\n session,\n sid,\n }\n}\n\n/**\n * Extends the session `sid` so it lasts at least another `sessionExpiration`. Sessions that already\n * last longer, like ones with a refresh token, keep their expiry, since their refresh token relies\n * on it.\n *\n * @returns The session, or `undefined` when the user has no session with this ID\n */\nexport const extendSession = async ({\n collectionConfig,\n req,\n sessionExpiration = collectionConfig.auth.tokenExpiration,\n sid,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n req: PayloadRequest\n /**\n * Seconds the session lasts at least, from now.\n *\n * @default collectionConfig.auth.tokenExpiration\n */\n sessionExpiration?: number\n sid: string\n user: AuthenticatedUser\n}): Promise<undefined | UserSession> => {\n assertNoValidationWrite(req)\n\n const session = user.sessions?.find(({ id }) => id === sid)\n\n if (!session) {\n return undefined\n }\n\n const expiresAt = new Date(Date.now() + sessionExpiration * 1000)\n\n if (new Date(session.expiresAt) < expiresAt) {\n session.expiresAt = expiresAt\n }\n\n await req.payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n // Prevent updatedAt from being updated when only extending a session\n sessions: removeExpiredSessions(user.sessions!),\n updatedAt: null,\n },\n req,\n returning: false,\n })\n\n return session\n}\n\nexport const revokeSession = async ({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n sid: string\n user: null | User\n}): Promise<void> => {\n assertNoValidationWrite(req)\n\n if (collectionConfig.auth.useSessions && user && user.sessions?.length) {\n user.sessions = user.sessions.filter((session) => session.id !== sid)\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n returning: false,\n })\n }\n}\n"],"names":["v4","uuid","assertNoValidationWrite","removeExpiredSessions","sessions","now","Date","filter","expiresAt","expiry","addSessionToUser","type","collectionConfig","label","metadata","payload","req","sessionExpiration","auth","tokenExpiration","user","session","sid","useSessions","getTime","id","createdAt","length","push","db","updateOne","collection","slug","data","updatedAt","returning","_strategy","extendSession","find","undefined","revokeSession"],"mappings":"AAAA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAMjC,SAASC,uBAAuB,QAAQ,0CAAyC;AAEjF;;CAEC,GACD,OAAO,MAAMC,wBAAwB,CAACC;IACpC,MAAMC,MAAM,IAAIC;IAEhB,OAAOF,SAASG,MAAM,CAAC,CAAC,EAAEC,SAAS,EAAE;QACnC,MAAMC,SAASD,qBAAqBF,OAAOE,YAAY,IAAIF,KAAKE;QAChE,OAAOC,SAASJ;IAClB;AACF,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMK,mBAAmB,OAAO,EACrCC,IAAI,EACJC,gBAAgB,EAChBC,KAAK,EACLC,QAAQ,EACRC,OAAO,EACPC,GAAG,EACHC,oBAAoBL,iBAAiBM,IAAI,CAACC,eAAe,EACzDC,IAAI,EAY8C;IAIlDlB,wBAAwBc;IAExB,IAAIK;IACJ,IAAIC;IACJ,IAAIV,iBAAiBM,IAAI,CAACK,WAAW,EAAE;QACrC,sBAAsB;QACtBD,MAAMrB;QACN,MAAMI,MAAM,IAAIC;QAChB,MAAME,YAAY,IAAIF,KAAKD,IAAImB,OAAO,KAAKP,oBAAoB;QAE/DI,UAAU;YAAEI,IAAIH;YAAKX;YAAMe,WAAWrB;YAAKG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ACb;QACAlB;QACAmB,WAAW;IACb;IAEA,OAAOd;AACT,EAAC;AAED,OAAO,MAAMmB,gBAAgB,OAAO,EAClC5B,gBAAgB,EAChBG,OAAO,EACPC,GAAG,EACHM,GAAG,EACHF,IAAI,EAOL;IACClB,wBAAwBc;IAExB,IAAIJ,iBAAiBM,IAAI,CAACK,WAAW,IAAIH,QAAQA,KAAKhB,QAAQ,EAAEuB,QAAQ;QACtEP,KAAKhB,QAAQ,GAAGgB,KAAKhB,QAAQ,CAACG,MAAM,CAAC,CAACc,UAAYA,QAAQI,EAAE,KAAKH;QACjE,MAAMP,QAAQc,EAAE,CAACC,SAAS,CAAC;YACzBL,IAAIL,KAAKK,EAAE;YACXM,YAAYnB,iBAAiBoB,IAAI;YACjCC,MAAMb;YACNJ;YACAmB,WAAW;QACb;IACF;AACF,EAAC"}
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -129,6 +129,10 @@ export type UserSession = {
|
|
|
129
129
|
createdAt?: Date | null | string;
|
|
130
130
|
expiresAt: Date | string;
|
|
131
131
|
id: string;
|
|
132
|
+
/** What the session is, for people to read, e.g. "Claude Code" or "Chrome on macOS". */
|
|
133
|
+
label?: null | string;
|
|
134
|
+
/** More to show next to the label, e.g. `{ redirectHost: 'claude.ai' }`. Never anything secret. */
|
|
135
|
+
metadata?: null | Record<string, unknown>;
|
|
132
136
|
/**
|
|
133
137
|
* How many times the session was refreshed with a refresh token. Refresh tokens remember it, so
|
|
134
138
|
* the latest one can be told apart from older ones.
|
|
@@ -136,6 +140,11 @@ export type UserSession = {
|
|
|
136
140
|
refreshCount?: null | number;
|
|
137
141
|
/** When the session was last refreshed with a refresh token. */
|
|
138
142
|
refreshedAt?: Date | null | string;
|
|
143
|
+
/**
|
|
144
|
+
* How the session was created: `'login'` for a sign-in, or e.g. `'mcp'` for an MCP client the
|
|
145
|
+
* user allowed. Plugins can use their own values.
|
|
146
|
+
*/
|
|
147
|
+
type?: null | string;
|
|
139
148
|
};
|
|
140
149
|
type GenerateVerifyEmailHTML<TUser = any> = (args: {
|
|
141
150
|
req: PayloadRequest;
|