From ef2dc724fd45248f31a7ece1333864c2796df1ce Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Mon, 16 Nov 2020 01:26:51 +0530 Subject: [PATCH] :recycle: Get subgroup scopes on login --- src/modules/auth/auth.service.ts | 41 ++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index a496c740e..1b831b84f 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -660,19 +660,40 @@ export class AuthService { where: { user: { id: user.id } }, select: { id: true, role: true, group: { select: { id: true } } }, }); - memberships.forEach((membership) => { + for await (const membership of memberships) { scopes.push(`membership-${membership.id}:*`); - if (membership.role === 'OWNER') - scopes.push(`group-${membership.group.id}:*`); + const ids = [ + membership.group.id, + ...(await this.recursivelyGetSubgroupIds(membership.group.id)), + ]; - // Admins cannot delete a group, but they can read/write - if (membership.role === 'ADMIN') - scopes.push(`group-${membership.group.id}:write-*`); + ids.forEach((id) => { + if (membership.role === 'OWNER') scopes.push(`group-${id}:*`); + // Admins cannot delete a group, but they can read/write + if (membership.role === 'ADMIN') scopes.push(`group-${id}:write-*`); + // Non-owners (admins and regular members) can also read + if (membership.role !== 'OWNER') scopes.push(`group-${id}:read-*`); + }); + } + return scopes; + } - // Non-owners (admins and regular members) can also read - if (membership.role !== 'OWNER') - scopes.push(`group-${membership.group.id}:read-*`); + private async recursivelyGetSubgroupIds(groupId: number) { + const subgroups = await this.prisma.groups.findMany({ + where: { parent: { id: groupId } }, + select: { + id: true, + parent: { select: { id: true } }, + subgroups: { select: { id: true } }, + }, }); - return scopes; + const ids = subgroups.map((i) => i.id); + for await (const group of subgroups) { + for await (const subgroup of group.subgroups) { + const recurisiveIds = await this.recursivelyGetSubgroupIds(subgroup.id); + ids.push(...recurisiveIds); + } + } + return ids; } }