Skip to content

Node.js based forum software built for the modern web

feat: add a write API route for custom user fields (#14840)

palmoni539910850e874
diff --git a/public/openapi/write.yaml b/public/openapi/write.yaml
index 8abad63f9b..6cd7250e37 100644
--- a/public/openapi/write.yaml
+++ b/public/openapi/write.yaml
@@ -286,6 +286,8 @@ paths:
$ref: 'write/intents/query/handle.yaml'
/admin/settings/{setting}:
$ref: 'write/admin/settings/setting.yaml'
+ /admin/users/custom-fields:
+ $ref: 'write/admin/users/custom-fields.yaml'
/admin/analytics:
$ref: 'write/admin/analytics.yaml'
/admin/analytics/{set}:
diff --git a/public/openapi/write/admin/users/custom-fields.yaml b/public/openapi/write/admin/users/custom-fields.yaml
new file mode 100644
index 0000000000..b678be988e
--- /dev/null
+++ b/public/openapi/write/admin/users/custom-fields.yaml
@@ -0,0 +1,63 @@
+put:
+ tags:
+ - admin
+ summary: save custom user fields
+ description: This operation replaces the full set of custom user profile fields with the ones supplied, in the order supplied. The calling user must have the `admin:users` privilege (or be a superadmin) in order for this call to proceed.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ fields:
+ type: array
+ description: the complete ordered list of custom user fields
+ example:
+ - key: pronouns
+ name: Pronouns
+ icon: fa-user
+ type: input-text
+ select-options: ''
+ visibility: all
+ min:rep: 0
+ items:
+ type: object
+ properties:
+ key:
+ type: string
+ description: unique identifier of the field
+ example: pronouns
+ name:
+ type: string
+ description: label shown to users
+ example: Pronouns
+ icon:
+ type: string
+ example: fa-user
+ type:
+ type: string
+ example: input-text
+ select-options:
+ type: string
+ description: newline separated list of options, for select fields
+ visibility:
+ type: string
+ example: all
+ min:rep:
+ type: string
+ description: reputation required before the field is shown
+ example: 0
+ responses:
+ '200':
+ description: custom user fields saved
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ $ref: ../../../components/schemas/Status.yaml#/Status
+ response:
+ type: object
+ properties: {}
diff --git a/src/api/admin.js b/src/api/admin.js
index a9d8be8259..f8f13f2891 100644
--- a/src/api/admin.js
+++ b/src/api/admin.js
@@ -9,6 +9,8 @@ const groups = require('../groups');
const plugins = require('../plugins');
const events = require('../events');
const postsCache = require('../posts/cache');
+const db = require('../database');
+const user = require('../user');
const adminApi = module.exports;
@@ -21,6 +23,43 @@ adminApi.updateSetting = async (caller, { setting, value }) => {
await meta.configs.set(setting, value);
};
+adminApi.users = {};
+
+adminApi.users.saveCustomFields = async (caller, { fields }) => {
+ const ok = await privileges.admin.can('admin:users', caller.uid);
+ if (!ok) {
+ throw new Error('[[error:no-privileges]]');
+ }
+ if (!Array.isArray(fields)) {
+ throw new Error('[[error:invalid-data]]');
+ }
+ const protectedFields = [
+ ...await user.getUserFieldWhitelist(),
+ ...user.protectedFields,
+ ];
+ for (const field of fields) {
+ if (!field || !field.key) {
+ throw new Error('[[error:invalid-data]]');
+ }
+ if (protectedFields.includes(field.key) || protectedFields.includes(field.key.toLowerCase())) {
+ throw new Error(`[[error:invalid-custom-user-field, ${field.key}]]`);
+ }
+ }
+ const keys = await db.getSortedSetRange('user-custom-fields', 0, -1);
+ await db.delete('user-custom-fields');
+ await db.deleteAll(keys.map(k => `user-custom-field:${k}`));
+
+ await db.sortedSetAdd(
+ 'user-custom-fields',
+ fields.map((f, i) => i),
+ fields.map(f => f.key)
+ );
+ await db.setObjectBulk(
+ fields.map(field => [`user-custom-field:${field.key}`, field])
+ );
+ await user.reloadCustomFieldWhitelist();
+};
+
adminApi.getAnalyticsKeys = async () => {
const keys = await analytics.getKeys();
diff --git a/src/controllers/write/admin.js b/src/controllers/write/admin.js
index 14cd24d3e7..d4738488a1 100644
--- a/src/controllers/write/admin.js
+++ b/src/controllers/write/admin.js
@@ -38,6 +38,12 @@ Admin.updateSetting = async (req, res) => {
helpers.formatApiResponse(200, res);
};
+Admin.saveCustomUserFields = async (req, res) => {
+ await api.admin.users.saveCustomFields(req, { fields: req.body.fields });
+
+ helpers.formatApiResponse(200, res);
+};
+
Admin.getAnalyticsKeys = async (req, res) => {
helpers.formatApiResponse(200, res, {
keys: await api.admin.getAnalyticsKeys(),
diff --git a/src/routes/write/admin.js b/src/routes/write/admin.js
index 8f4c039cbc..3bf038f719 100644
--- a/src/routes/write/admin.js
+++ b/src/routes/write/admin.js
@@ -12,6 +12,8 @@ module.exports = function () {
setupApiRoute(router, 'put', '/settings/:setting', [...middlewares, middleware.checkRequired.bind(null, ['value'])], controllers.write.admin.updateSetting);
+ setupApiRoute(router, 'put', '/users/custom-fields', [...middlewares, middleware.checkRequired.bind(null, ['fields'])], controllers.write.admin.saveCustomUserFields);
+
setupApiRoute(router, 'get', '/analytics', [...middlewares], controllers.write.admin.getAnalyticsKeys);
setupApiRoute(router, 'get', '/analytics/:set', [...middlewares], controllers.write.admin.getAnalyticsData);
const requireAPIReAuth = middleware.requireAPIReAuth();
diff --git a/src/socket.io/admin/user.js b/src/socket.io/admin/user.js
index 096e498aff..a11fffccee 100644
--- a/src/socket.io/admin/user.js
+++ b/src/socket.io/admin/user.js
@@ -11,6 +11,7 @@ const user = require('../../user');
const events = require('../../events');
const utils = require('../../utils');
const sockets = require('..');
+const api = require('../../api');
const User = module.exports;
@@ -157,28 +158,7 @@ User.exportUsersCSV = async function (socket, data) {
};
User.saveCustomFields = async function (socket, fields) {
- const protectedFields = [
- ...await user.getUserFieldWhitelist(),
- ...user.protectedFields,
- ];
- for (const field of fields) {
- if (protectedFields.includes(field.key) || protectedFields.includes(field.key.toLowerCase())) {
- throw new Error(`[[error:invalid-custom-user-field, ${field.key}]]`);
- }
- }
- const keys = await db.getSortedSetRange('user-custom-fields', 0, -1);
- await db.delete('user-custom-fields');
- await db.deleteAll(keys.map(k => `user-custom-field:${k}`));
-
- await db.sortedSetAdd(
- `user-custom-fields`,
- fields.map((f, i) => i),
- fields.map(f => f.key)
- );
- await db.setObjectBulk(
- fields.map(field => [`user-custom-field:${field.key}`, field])
- );
- await user.reloadCustomFieldWhitelist();
+ await api.admin.users.saveCustomFields(socket, { fields });
};
User.saveCustomReasons = async function (socket, reasons) {
diff --git a/test/controllers-admin.js b/test/controllers-admin.js
index e230150062..177f95ce74 100644
--- a/test/controllers-admin.js
+++ b/test/controllers-admin.js
@@ -643,6 +643,51 @@ describe('Admin Controllers', () => {
plugins.hooks.unregister('somePlugin', 'filter:config.get', onConfigGet);
});
+ describe('custom user fields', () => {
+ after(async () => {
+ await helpers.request('put', '/api/v3/admin/users/custom-fields', {
+ jar: jar,
+ body: { fields: [] },
+ });
+ });
+
+ it('should save custom user fields', async () => {
+ const { response } = await helpers.request('put', '/api/v3/admin/users/custom-fields', {
+ jar: jar,
+ body: {
+ fields: [
+ { key: 'pronouns', name: 'Pronouns', type: 'input-text' },
+ { key: 'location', name: 'Location', type: 'input-text' },
+ ],
+ },
+ });
+ assert.strictEqual(response.statusCode, 200);
+
+ const keys = await db.getSortedSetRange('user-custom-fields', 0, -1);
+ assert.deepStrictEqual(keys, ['pronouns', 'location']);
+ const field = await db.getObject('user-custom-field:pronouns');
+ assert.strictEqual(field.name, 'Pronouns');
+ });
+
+ it('should reject a field that collides with a core user field', async () => {
+ const { response, body } = await helpers.request('put', '/api/v3/admin/users/custom-fields', {
+ jar: jar,
+ body: { fields: [{ key: 'username', name: 'Username', type: 'input-text' }] },
+ });
+ assert.strictEqual(response.statusCode, 400);
+ assert.strictEqual(body.status.code, 'bad-request');
+ });
+
+ it('should not allow a regular user to save custom user fields', async () => {
+ const { jar: regularJar } = await helpers.loginUser('regular', 'regularpwd');
+ const { response } = await helpers.request('put', '/api/v3/admin/users/custom-fields', {
+ jar: regularJar,
+ body: { fields: [] },
+ });
+ assert.strictEqual(response.statusCode, 403);
+ });
+ });
+
describe('admin page privileges', () => {
let uid;
const privileges = require('../src/privileges');