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.') }