From 907aa485fdf76ee5decc2f450ac27707fc636e7b Mon Sep 17 00:00:00 2001 From: Sabir Hassan Date: Fri, 24 Jun 2022 23:15:41 +0500 Subject: [PATCH] chore: throw error when creating duplicate permission --- api/src/controllers/permission.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/api/src/controllers/permission.ts b/api/src/controllers/permission.ts index c986d81..1fa2108 100644 --- a/api/src/controllers/permission.ts +++ b/api/src/controllers/permission.ts @@ -163,10 +163,17 @@ const createPermission = async ({ let group: GroupResponse | undefined switch (principalType) { - case 'user': + case 'user': { const userInDB = await User.findOne({ id: principalId }) if (!userInDB) throw new Error('User not found.') + const alreadyExists = await Permission.findOne({ + uri, + user: userInDB._id + }) + if (alreadyExists) + throw new Error('Permission already exists with provided URI and User.') + permission.user = userInDB._id user = { @@ -175,10 +182,20 @@ const createPermission = async ({ displayName: userInDB.displayName } break - case 'group': + } + case 'group': { const groupInDB = await Group.findOne({ groupId: principalId }) if (!groupInDB) throw new Error('Group not found.') + const alreadyExists = await Permission.findOne({ + uri, + group: groupInDB._id + }) + if (alreadyExists) + throw new Error( + 'Permission already exists with provided URI and Group.' + ) + permission.group = groupInDB._id group = { @@ -187,6 +204,7 @@ const createPermission = async ({ description: groupInDB.description } break + } default: throw new Error('Invalid principal type. Valid types are user or group.') }