From cc44bbaa4e3a434e4cb7903e18608fbb317a9c32 Mon Sep 17 00:00:00 2001 From: j-weissen Date: Tue, 27 Sep 2022 00:26:46 +0200 Subject: [PATCH] funktioniert, aber far from pretty --- .../strapi/src/api/note/controllers/note.js | 50 +++++++++++++++++-- backend/strapi/src/api/note/utils.js | 3 ++ 2 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 backend/strapi/src/api/note/utils.js diff --git a/backend/strapi/src/api/note/controllers/note.js b/backend/strapi/src/api/note/controllers/note.js index 65e3eb5..d4f095b 100644 --- a/backend/strapi/src/api/note/controllers/note.js +++ b/backend/strapi/src/api/note/controllers/note.js @@ -1,4 +1,8 @@ 'use strict'; +//move to utils! +function getNoteIdFromUrl(url) { + return Number(url.split("/").at(-1)); +} /** * note controller @@ -34,17 +38,55 @@ module.exports = createCoreController('api::note.note', ({strapi}) => ({ * @returns {Promise} */ async findOne(ctx) { - const noteId = Number(ctx.request.url.split("/").at(-1)); + const noteId = getNoteIdFromUrl(ctx.request.url); const userId = ctx.state.user.id; const entry = await strapi.entityService.findOne('api::note.note', noteId, { populate: ['owners'], }); - let allowed = entry.owners.some(owner => owner.id === userId) - if (allowed) { + const authorized = entry.owners.some(owner => owner.id === userId) + if (authorized) { return JSON.stringify(entry); } else { ctx.response.status = 403; } }, - + async update(ctx) { + const noteId = getNoteIdFromUrl(ctx.request.url) + const userId = ctx.state.user.id; + const requestBody = ctx.request.body; + const entry = await strapi.entityService.findOne('api::note.note', noteId, { + populate: ['owners'], + }); + const authorized = entry.owners.some(owner => owner.id === userId) + const allowed = !requestBody.data.hasOwnProperty("owners"); + if (!authorized) { + ctx.response.status = 403; + } else if (!allowed) { + ctx.response.status = 400; + } else { + super.update(ctx); + } + }, + async delete(ctx) { + const noteId = getNoteIdFromUrl(ctx.request.url) + const userId = ctx.state.user.id; + const entry = await strapi.entityService.findOne('api::note.note', noteId, { + populate: ['owners'], + }); + const ownersCount = entry.owners.length; + const authorized = entry.owners.some(owner => owner.id === userId) + if (!authorized) { + ctx.response.status = 403; + return; + } + if (ownersCount === 1) { + super.delete(ctx); + } else { + strapi.entityService.update('api::note.note', noteId, { + data: { + owners: entry.owners.filter(owner => owner.id !== userId) + } + }) + } + } })); diff --git a/backend/strapi/src/api/note/utils.js b/backend/strapi/src/api/note/utils.js new file mode 100644 index 0000000..63a054e --- /dev/null +++ b/backend/strapi/src/api/note/utils.js @@ -0,0 +1,3 @@ +function getNoteIdFromUrl(url) { + return Number(url.split("/").at(-1)); +}