Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist and serve user preferences #1184

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions lib/http/endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,40 @@ const defaultEndpoint = endpointBase({
errorWriter: defaultErrorWriter
});

const simpleResultWriter = (result, request, response, next) => {
// Expects a `result` with optional keys `body`, `status` and `headers`.
// No validation.
if (result.headers !== undefined) {
for (const [headername, headervalue] of Object.entries(result.headers)) {
response.setHeader(headername, headervalue);
}
}

if (result.status !== undefined) {
response.statusCode = result.status;
}

if (result.body !== undefined) {
if (result.body instanceof PartialPipe) {
result.body.streams.at(-1).on('error', streamErrorHandler(response));
result.body.with(response).pipeline((err) => next?.(err));
} else if (result.body.pipe != null) {
result.body.on('error', streamErrorHandler(response));
pipeline(result.body, response, (err) => err && next?.(err));
} else {
response.send(result.body);
}
} else {
// No body.
response.send();
}
};

const simpleEndpoint = endpointBase({
resultWriter: simpleResultWriter,
errorWriter: defaultErrorWriter,
});

brontolosone marked this conversation as resolved.
Show resolved Hide resolved
const htmlEndpoint = endpointBase({
resultWriter: (result, request, response) => {
response.type('text/html');
Expand Down Expand Up @@ -394,6 +428,7 @@ const odataXmlEndpoint = endpointBase({

const builder = (container, preprocessors) => {
const result = defaultEndpoint(container, preprocessors);
result.simple = simpleEndpoint(container, preprocessors);
result.html = htmlEndpoint(container, preprocessors);
result.openRosa = openRosaEndpoint(container, preprocessors);
result.odata = {
Expand Down
1 change: 1 addition & 0 deletions lib/http/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ module.exports = (container) => {
require('../resources/datasets')(service, endpoint);
require('../resources/entities')(service, endpoint);
require('../resources/oidc')(service, endpoint);
require('../resources/user-preferences')(service, endpoint);

////////////////////////////////////////////////////////////////////////////////
// POSTRESOURCE HANDLERS
Expand Down
3 changes: 2 additions & 1 deletion lib/model/container.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ const withDefaults = (base, queries) => {
SubmissionAttachments: require('./query/submission-attachments'),
Users: require('./query/users'),
Datasets: require('./query/datasets'),
Entities: require('./query/entities')
Entities: require('./query/entities'),
UserPreferences: require('./query/user-preferences')
};

return injector(base, mergeRight(defaultQueries, queries));
Expand Down
35 changes: 35 additions & 0 deletions lib/model/migrations/20240910-01-add-user_preferences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2024 ODK Central Developers
brontolosone marked this conversation as resolved.
Show resolved Hide resolved
// See the NOTICE file at the top-level directory of this distribution and at
// https://github.com/getodk/central-backend/blob/master/NOTICE.
// This file is part of ODK Central. It is subject to the license terms in
// the LICENSE file found in the top-level directory of this distribution and at
// https://www.apache.org/licenses/LICENSE-2.0. No part of ODK Central,
// including this file, may be copied, modified, propagated, or distributed
// except according to the terms contained in the LICENSE file.

const up = (db) => db.raw(`
CREATE TABLE user_site_preferences (
"userId" integer NOT NULL REFERENCES users ("actorId"),
"propertyName" text NOT NULL CHECK (length("propertyName") > 0),
"propertyValue" jsonb NOT NULL,
CONSTRAINT "user_site_preferences_primary_key" PRIMARY KEY ("userId", "propertyName")
);

CREATE TABLE user_project_preferences (
"userId" integer NOT NULL REFERENCES users ("actorId"),
"projectId" integer NOT NULL REFERENCES projects ("id"),
"propertyName" text NOT NULL CHECK (length("propertyName") > 0),
"propertyValue" jsonb NOT NULL,
CONSTRAINT "user_project_preferences_primary_key" PRIMARY KEY ("userId", "projectId", "propertyName")
);

-- Primary key indices are used for PUTing/DELETE-ing individual rows — but the below indices are
-- used when aggregating all of a user's preferences.
CREATE INDEX ON "user_site_preferences" ("userId");
CREATE INDEX ON "user_project_preferences" ("userId");
`);

const down = (db) => Promise.all([db.schema.dropTable('user_site_preferences'), db.schema.dropTable('user_project_preferences')]);
brontolosone marked this conversation as resolved.
Show resolved Hide resolved

module.exports = { up, down };

117 changes: 117 additions & 0 deletions lib/model/query/user-preferences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright 2024 ODK Central Developers
// See the NOTICE file at the top-level directory of this distribution and at
// https://github.com/getodk/central-backend/blob/master/NOTICE.
// This file is part of ODK Central. It is subject to the license terms in
// the LICENSE file found in the top-level directory of this distribution and at
// https://www.apache.org/licenses/LICENSE-2.0. No part of ODK Central,
// including this file, may be copied, modified, propagated, or distributed
// except according to the terms contained in the LICENSE file.

const { sql } = require('slonik');


const getForUser = (userId) => ({ one }) =>
one(sql`
SELECT
(
SELECT
jsonb_build_object(
'projects',
coalesce(
jsonb_object_agg(
projprops."projectId",
projprops.props
),
jsonb_build_object()
)
)
FROM
(
SELECT
"projectId",
jsonb_object_agg("propertyName", "propertyValue") AS props
FROM
user_project_preferences
WHERE
"userId" = ${userId}
GROUP BY
"projectId"
) AS projprops
)
||
(
SELECT
jsonb_build_object(
'site',
coalesce(
jsonb_object_agg(
user_site_preferences."propertyName",
user_site_preferences."propertyValue"
),
jsonb_build_object()
)
)
FROM
user_site_preferences
WHERE
"userId" = ${userId}
)
AS preferences
`);


const _writeProperty = (tablename, subject, userId, propertyName, propertyValue) => ({ one }) => {
const targetColumns = ['userId', 'propertyName', 'propertyValue']
.concat((subject === null) ? [] : ['projectId'])
.map(el => sql.identifier([el]));

const values = [userId, propertyName, sql.json(propertyValue)]
.concat((subject === null) ? [] : [subject]);

return one(sql`
INSERT INTO ${sql.identifier([tablename])}
(${sql.join(targetColumns, `, `)})
VALUES
(${sql.join(values, `, `)})
ON CONFLICT ON CONSTRAINT ${sql.identifier([`${tablename}_primary_key`])}
DO UPDATE
SET "propertyValue" = ${sql.json(propertyValue)}
RETURNING
1 AS "modified_count"
`);
};


const _removeProperty = (tablename, subject, userId, propertyName) => ({ maybeOne }) => {
const targetColumns = ['userId', 'propertyName']
.concat((subject === null) ? [] : ['projectId'])
.map(el => sql.identifier([el]));

const values = [userId, propertyName]
.concat((subject === null) ? [] : [subject]);

return maybeOne(sql`
DELETE FROM ${sql.identifier([tablename])}
WHERE
(${sql.join(targetColumns, `, `)})
=
(${sql.join(values, `, `)})
RETURNING
1 AS "delcnt"
`);
};


const writeSiteProperty = (userId, propertyName, propertyValue) => ({ one }) =>
_writeProperty('user_site_preferences', null, userId, propertyName, propertyValue)({ one });

const removeSiteProperty = (userId, propertyName) => ({ maybeOne }) =>
_removeProperty('user_site_preferences', null, userId, propertyName)({ maybeOne });

const writeProjectProperty = (userId, projectId, propertyName, propertyValue) => ({ one }) =>
_writeProperty('user_project_preferences', projectId, userId, propertyName, propertyValue)({ one });

const removeProjectProperty = (userId, projectId, propertyName) => ({ maybeOne }) =>
_removeProperty('user_project_preferences', projectId, userId, propertyName)({ maybeOne });

module.exports = { removeSiteProperty, writeSiteProperty, writeProjectProperty, removeProjectProperty, getForUser };
6 changes: 5 additions & 1 deletion lib/model/query/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
const { sql } = require('slonik');
const { map } = require('ramda');
const { Actor, User } = require('../frames');
const { getForUser } = require('./user-preferences');
const { hashPassword } = require('../../util/crypto');
const { unjoiner, page, equals, QueryOptions } = require('../../util/db');
const { reject } = require('../../util/promise');
Expand Down Expand Up @@ -86,10 +87,13 @@ const emailEverExisted = (email) => ({ maybeOne }) =>
maybeOne(sql`select true from users where email=${email} limit 1`)
.then((user) => user.isDefined());

const getPreferences = (userId) => ({ one }) => getForUser(userId)({ one });
brontolosone marked this conversation as resolved.
Show resolved Hide resolved

module.exports = {
create, update,
updatePassword, invalidatePassword, provisionPasswordResetToken,
getAll, getByEmail, getByActorId,
emailEverExisted
emailEverExisted,
getPreferences,
};

63 changes: 63 additions & 0 deletions lib/resources/user-preferences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright 2024 ODK Central Developers
// See the NOTICE file at the top-level directory of this distribution and at
// https://github.com/getodk/central-backend/blob/master/NOTICE.
// This file is part of ODK Central. It is subject to the license terms in
// the LICENSE file found in the top-level directory of this distribution and at
// https://www.apache.org/licenses/LICENSE-2.0. No part of ODK Central,
// including this file, may be copied, modified, propagated, or distributed
// except according to the terms contained in the LICENSE file.

const { always } = require('ramda');
const Problem = require('../util/problem');
const { getOrNotFound } = require('../util/promise');

module.exports = (service, endpoint) => {

//////////////////////////////////////////////////////////////////////////////
// User preferences (UI settings)

//////////////////////////////////////////////////////////////////////////////
// Endpoint to get all of a user's preferences.
// For completeness and ease of debugging; as these preferences are normally
// pulled in by the frontend through the extended version of /users/current.
service.get('/user-preferences', endpoint.simple(({ UserPreferences }, { auth }) => {
if (auth.actor.value === undefined) return Problem.user.insufficientRights();
return UserPreferences.getForUser(auth.actor.value.id)
.then(res => ({ headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: res.preferences }));
}));
brontolosone marked this conversation as resolved.
Show resolved Hide resolved

//////////////
// Per-project
service.put('/user-preferences/project/:projectId/:propertyName', endpoint.simple(({ UserPreferences }, { body, auth, params }) => {
// Expects a body of {"propertyValue": X}, where X will go into the propertyValue column.
if (body.propertyValue === undefined) return Problem.user.propertyNotFound({ property: 'propertyValue' });
if (auth.actor.value === undefined) return Problem.user.insufficientRights();
return UserPreferences.writeProjectProperty(auth.actor.value.id, params.projectId, params.propertyName, body.propertyValue)
.then(always({ status: 201 }));
}));

service.delete('/user-preferences/project/:projectId/:propertyName', endpoint.simple(({ UserPreferences }, { auth, params }) => {
if (auth.actor.value === undefined) return Problem.user.insufficientRights();
return UserPreferences.removeProjectProperty(auth.actor.value.id, params.projectId, params.propertyName)
.then(getOrNotFound)
.then(always({ status: 204 }));
}));

///////////
// Sitewide
service.delete('/user-preferences/site/:propertyName', endpoint.simple(({ UserPreferences }, { auth, params }) => {
if (auth.actor.value === undefined) return Problem.user.insufficientRights();
return UserPreferences.removeSiteProperty(auth.actor.value.id, params.propertyName)
.then(getOrNotFound)
.then(always({ status: 204 }));
}));

service.put('/user-preferences/site/:propertyName', endpoint.simple(({ UserPreferences }, { body, auth, params }) => {
// Expects a body of {"propertyValue": X}, where X will go into the propertyValue column.
if (body.propertyValue === undefined) return Problem.user.propertyNotFound({ property: 'propertyValue' });
if (auth.actor.value === undefined) return Problem.user.insufficientRights();
return UserPreferences.writeSiteProperty(auth.actor.value.id, params.propertyName, body.propertyValue)
.then(always({ status: 201 }));
}));

};
3 changes: 2 additions & 1 deletion lib/resources/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ module.exports = (service, endpoint) => {
auth.actor.map((actor) =>
((queryOptions.extended === true)
? Promise.all([ Users.getByActorId(actor.id).then(getOrNotFound), Auth.verbsOn(actor.id, '*') ])
.then(([ user, verbs ]) => Object.assign({ verbs }, user.forApi()))
.then(([ user, verbs ]) => Users.getPreferences(user.actorId)
brontolosone marked this conversation as resolved.
Show resolved Hide resolved
.then((preferences) => Object.assign(Object.assign({ verbs }, user.forApi()), preferences)))
brontolosone marked this conversation as resolved.
Show resolved Hide resolved
: Users.getByActorId(actor.id).then(getOrNotFound)))
.orElse(Problem.user.notFound())));

Expand Down
Loading