Skip to content

Commit 779f06f

Browse files
fix: run the password field's validation on reset password (3.x) (#18980)
Reset password now runs the collection's `password` field validation, the same as create and update do. Before this change, a `password` field override (such as `minLength: 8` or a custom `validate`) did not apply to resets, so a user could reset their password to `abc`. Fixes #18823 --------- Co-authored-by: Jarrod Flesch <[email protected]>
1 parent 9e6d237 commit 779f06f

4 files changed

Lines changed: 172 additions & 2 deletions

File tree

‎packages/payload/src/auth/operations/resetPassword.ts‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
import { status as httpStatus } from 'http-status'
22

3-
import type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'
3+
import type {
4+
Collection,
5+
DataFromCollectionSlug,
6+
SanitizedCollectionConfig,
7+
} from '../../collections/config/types.js'
8+
import type { Validate } from '../../fields/config/types.js'
49
import type { AuthCollectionSlug, TypedUser } from '../../index.js'
510
import type { PayloadRequest } from '../../types/index.js'
611

712
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'
813
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'
9-
import { APIError, Forbidden } from '../../errors/index.js'
14+
import { APIError, Forbidden, ValidationError } from '../../errors/index.js'
1015
import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'
1116
import { commitTransaction } from '../../utilities/commitTransaction.js'
1217
import { initTransaction } from '../../utilities/initTransaction.js'
@@ -96,6 +101,14 @@ export const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(
96101
throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)
97102
}
98103

104+
await validatePasswordField({
105+
collectionConfig,
106+
overrideAccess,
107+
password: data.password,
108+
req,
109+
user,
110+
})
111+
99112
// TODO: replace this method
100113
const { hash, salt } = await generatePasswordSaltHash({
101114
collection: collectionConfig,
@@ -266,3 +279,51 @@ export const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(
266279
throw error
267280
}
268281
}
282+
283+
/**
284+
* Runs the `password` field override's validation, which `payload.db.updateOne` skips.
285+
*/
286+
async function validatePasswordField({
287+
collectionConfig,
288+
overrideAccess,
289+
password,
290+
req,
291+
user,
292+
}: {
293+
collectionConfig: SanitizedCollectionConfig
294+
overrideAccess: boolean
295+
password: string
296+
req: PayloadRequest
297+
user: TypedUser
298+
}): Promise<void> {
299+
const passwordField = collectionConfig.flattenedFields.find((field) => field.name === 'password')
300+
301+
if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {
302+
return
303+
}
304+
305+
const validate = passwordField.validate as Validate<string>
306+
const dataToValidate = { ...user, password }
307+
308+
const validationResult = await validate(password, {
309+
...passwordField,
310+
id: user.id,
311+
blockData: {},
312+
collectionSlug: collectionConfig.slug,
313+
data: dataToValidate,
314+
event: 'submit',
315+
operation: 'update',
316+
overrideAccess,
317+
path: ['password'],
318+
preferences: { fields: {} },
319+
req,
320+
siblingData: dataToValidate,
321+
})
322+
323+
if (typeof validationResult === 'string') {
324+
throw new ValidationError({
325+
collection: collectionConfig.slug,
326+
errors: [{ message: validationResult, path: 'password' }],
327+
})
328+
}
329+
}

‎test/auth/config.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import {
1010
BASE_PATH,
1111
namedSaveToJWTValue,
1212
partialDisableLocalStrategiesSlug,
13+
passwordCustomValidateSlug,
14+
passwordMinLengthSlug,
1315
publicUsersSlug,
1416
saveToJWTKey,
1517
slug,
@@ -297,6 +299,31 @@ export default buildConfigWithDefaults({
297299
singular: 'API Key',
298300
},
299301
},
302+
{
303+
slug: passwordMinLengthSlug,
304+
auth: true,
305+
fields: [
306+
{
307+
name: 'password',
308+
type: 'text',
309+
hidden: true,
310+
minLength: 8,
311+
},
312+
],
313+
},
314+
{
315+
slug: passwordCustomValidateSlug,
316+
auth: true,
317+
fields: [
318+
{
319+
name: 'password',
320+
type: 'text',
321+
hidden: true,
322+
validate: (value: null | string | undefined) =>
323+
!value || /\d/.test(value) || 'Password must contain a number',
324+
},
325+
],
326+
},
300327
{
301328
slug: publicUsersSlug,
302329
auth: {

‎test/auth/int.spec.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import {
2727
apiKeysSlug,
2828
namedSaveToJWTValue,
2929
partialDisableLocalStrategiesSlug,
30+
passwordCustomValidateSlug,
31+
passwordMinLengthSlug,
3032
preferencesSlug,
3133
publicUsersSlug,
3234
saveToJWTKey,
@@ -2434,6 +2436,82 @@ describe('Auth', () => {
24342436
).rejects.toThrow('Token is either invalid or has expired.')
24352437
})
24362438

2439+
describe('reset password with a password field override', () => {
2440+
const userEmail = '[email protected]'
2441+
2442+
afterEach(async () => {
2443+
for (const collection of [passwordMinLengthSlug, passwordCustomValidateSlug] as const) {
2444+
await payload.delete({
2445+
collection,
2446+
where: { email: { equals: userEmail } },
2447+
})
2448+
}
2449+
})
2450+
2451+
it('should reject a new password shorter than the field minLength', async () => {
2452+
await payload.create({
2453+
collection: passwordMinLengthSlug,
2454+
data: { email: userEmail, password: 'longenough1' },
2455+
})
2456+
2457+
const token = await payload.forgotPassword({
2458+
collection: passwordMinLengthSlug,
2459+
data: { email: userEmail },
2460+
disableEmail: true,
2461+
})
2462+
2463+
await expect(
2464+
payload.resetPassword({
2465+
collection: passwordMinLengthSlug,
2466+
data: { password: 'abc', token },
2467+
overrideAccess: true,
2468+
}),
2469+
).rejects.toThrow('The following field is invalid: password')
2470+
})
2471+
2472+
it('should reject a new password that fails the field custom validate', async () => {
2473+
await payload.create({
2474+
collection: passwordCustomValidateSlug,
2475+
data: { email: userEmail, password: 'hasnumber1' },
2476+
})
2477+
2478+
const token = await payload.forgotPassword({
2479+
collection: passwordCustomValidateSlug,
2480+
data: { email: userEmail },
2481+
disableEmail: true,
2482+
})
2483+
2484+
await expect(
2485+
payload.resetPassword({
2486+
collection: passwordCustomValidateSlug,
2487+
data: { password: 'nonumber', token },
2488+
overrideAccess: true,
2489+
}),
2490+
).rejects.toThrow('The following field is invalid: password')
2491+
})
2492+
2493+
it('should accept a new password that meets the field minLength', async () => {
2494+
await payload.create({
2495+
collection: passwordMinLengthSlug,
2496+
data: { email: userEmail, password: 'longenough1' },
2497+
})
2498+
2499+
const token = await payload.forgotPassword({
2500+
collection: passwordMinLengthSlug,
2501+
data: { email: userEmail },
2502+
disableEmail: true,
2503+
})
2504+
2505+
const reset = await payload.resetPassword({
2506+
collection: passwordMinLengthSlug,
2507+
data: { password: 'longenough2', token },
2508+
overrideAccess: true,
2509+
})
2510+
2511+
expect(reset.user.email).toBe(userEmail)
2512+
})
2513+
})
2514+
24372515
describe('Login Attempts', () => {
24382516
const createdLoginAttemptUsers: Array<{
24392517
collection: typeof publicUsersSlug | typeof slug

‎test/auth/shared.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ export const publicUsersSlug = 'public-users'
66

77
export const apiKeysSlug = 'api-keys'
88

9+
export const passwordMinLengthSlug = 'password-min-length'
10+
11+
export const passwordCustomValidateSlug = 'password-custom-validate'
12+
913
export const jwtUsersSlug = 'jwt-users'
1014

1115
export const restrictedRelationshipsSlug = 'restricted-relationships'

0 commit comments

Comments
 (0)