funktioniert, aber far from pretty

This commit is contained in:
j-weissen 2022-09-27 00:26:46 +02:00
parent 834f1284fe
commit cc44bbaa4e
2 changed files with 49 additions and 4 deletions

View file

@ -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<string>}
*/
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)
}
})
}
}
}));

View file

@ -0,0 +1,3 @@
function getNoteIdFromUrl(url) {
return Number(url.split("/").at(-1));
}