diff --git a/packages/payload/src/auth/operations/resetPassword.ts b/packages/payload/src/auth/operations/resetPassword.ts index f6ff561e10a..b056a02b334 100644 --- a/packages/payload/src/auth/operations/resetPassword.ts +++ b/packages/payload/src/auth/operations/resetPassword.ts @@ -163,12 +163,49 @@ export const resetPasswordOperation = async ( const fieldsToSign = getFieldsToSign(fieldsToSignArgs) + // ///////////////////////////////////// + // beforeLogin - Collection + // ///////////////////////////////////// + + let userBeforeLogin = user + + if (collectionConfig.hooks?.beforeLogin?.length) { + for (const hook of collectionConfig.hooks.beforeLogin) { + userBeforeLogin = + (await hook({ + collection: args.collection?.config, + context: args.req.context, + req: args.req, + user: userBeforeLogin, + })) || userBeforeLogin + } + } + const { token } = await jwtSign({ fieldsToSign, secret, tokenExpiration: collectionConfig.auth.tokenExpiration, }) + req.user = userBeforeLogin + + // ///////////////////////////////////// + // afterLogin - Collection + // ///////////////////////////////////// + + if (collectionConfig.hooks?.afterLogin?.length) { + for (const hook of collectionConfig.hooks.afterLogin) { + userBeforeLogin = + (await hook({ + collection: args.collection?.config, + context: args.req.context, + req: args.req, + token, + user: userBeforeLogin, + })) || userBeforeLogin + } + } + const fullUser = await payload.findByID({ id: user.id, collection: collectionConfig.slug, diff --git a/test/hooks/int.spec.ts b/test/hooks/int.spec.ts index a2c409f4a6e..cced505a1fc 100644 --- a/test/hooks/int.spec.ts +++ b/test/hooks/int.spec.ts @@ -411,6 +411,47 @@ describe('Hooks', () => { expect(result.afterLoginHook).toStrictEqual(true) }) + it('should call afterLogin hook on password reset', async () => { + const resetUser = await payload.create({ + collection: hooksUsersSlug, + data: { + email: 'reset-test@payloadcms.com', + password: devUser.password, + roles: ['admin'], + afterLoginHook: false, + }, + }) + + expect(resetUser.afterLoginHook).toStrictEqual(false) + + const token = await payload.forgotPassword({ + collection: hooksUsersSlug, + data: { + email: resetUser.email, + }, + disableEmail: true, + }) + + const { user } = await payload.resetPassword({ + collection: hooksUsersSlug, + overrideAccess: true, + data: { + password: 'newPassword123', + token, + }, + }) + + expect(user).toBeDefined() + expect(user.afterLoginHook).toStrictEqual(true) + + const result = await payload.findByID({ + id: user.id, + collection: hooksUsersSlug, + }) + + expect(result.afterLoginHook).toStrictEqual(true) + }) + it('deny user login', async () => { await expect(() => payload.login({