fix: properly validates preferences json (#10465)

It is currently possible to set all types of valid JSON within the
`payload-preferences` collection via the REST API, but not the Local
API. For example, locales are currently saved as plain strings to the
`value` field, something that is only possible through REST. This is
because there is a custom POST handler that submits the data directly to
the db using the update operation itself, bypassing typical `json` field
validation. However, when using the Local API, it does not behave in the
same way, and throws a validation error instead. The fix is to add a
custom `validate` function to this field that attempts to parse the
value, and if it succeeds, returns true. This way both APIs behave the
same.
This commit is contained in:
Jacob Fletcher
2025-01-08 23:19:50 -05:00
committed by GitHub
parent 3349a4c5e5
commit 6a262ab809

View File

@@ -6,7 +6,9 @@ import { findByIDHandler } from './requestHandlers/findOne.js'
import { updateHandler } from './requestHandlers/update.js'
const preferenceAccess: Access = ({ req }) => {
if (!req.user) return false
if (!req.user) {
return false
}
return {
'user.value': {
@@ -51,6 +53,7 @@ const getPreferencesCollection = (config: Config): CollectionConfig => ({
if (!req?.user) {
return null
}
return {
relationTo: req?.user.collection,
value: req?.user.id,
@@ -72,6 +75,17 @@ const getPreferencesCollection = (config: Config): CollectionConfig => ({
{
name: 'value',
type: 'json',
validate: (value) => {
if (value) {
try {
JSON.parse(JSON.stringify(value))
} catch {
return 'Invalid JSON'
}
}
return true
},
},
],
lockDocuments: false,