Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

feat(users): allow to manage personal groups from the guest profile dialog

johavenc5d3c70c485e
diff --git a/backend/src/applications/users/dto/create-or-update-user.dto.ts b/backend/src/applications/users/dto/create-or-update-user.dto.ts
index a6acf23f..fb7d3fa1 100644
--- a/backend/src/applications/users/dto/create-or-update-user.dto.ts
+++ b/backend/src/applications/users/dto/create-or-update-user.dto.ts
@@ -47,7 +47,7 @@ export class OptionalUserDto {
@IsInt()
storageQuota?: number
- // for users
+ // for users and guests
@IsOptional()
@IsArray()
@IsInt({ each: true })
diff --git a/backend/src/applications/users/dto/search-members.dto.ts b/backend/src/applications/users/dto/search-members.dto.ts
index 34e9923a..1de8e07f 100644
--- a/backend/src/applications/users/dto/search-members.dto.ts
+++ b/backend/src/applications/users/dto/search-members.dto.ts
@@ -26,6 +26,14 @@ export class SearchMembersDto {
@IsBoolean()
excludePersonalGroups?: boolean = false
+ @IsOptional()
+ @IsBoolean()
+ onlyPersonalGroups?: boolean = false
+
+ @IsOptional()
+ @IsBoolean()
+ isGroupManager?: boolean = false
+
@IsOptional()
@IsInt()
usersRole?: number
diff --git a/backend/src/applications/users/interfaces/guest-user.interface.ts b/backend/src/applications/users/interfaces/guest-user.interface.ts
index d8cf4270..164b9292 100644
--- a/backend/src/applications/users/interfaces/guest-user.interface.ts
+++ b/backend/src/applications/users/interfaces/guest-user.interface.ts
@@ -4,4 +4,5 @@ import type { Member } from './member.interface'
export type GuestUser = Partial<User> & {
fullName: string
managers?: Member[]
+ groups?: Member[]
}
diff --git a/backend/src/applications/users/services/admin-users-manager.service.spec.ts b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
index 4998b5a4..9f11be8e 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.spec.ts
@@ -292,11 +292,41 @@ describe(AdminUsersManager.name, () => {
expect(res).toEqual(updatedGuest)
})
+ it('update guest + groups diff', async () => {
+ const guest = {
+ id: 33,
+ login: 'g',
+ email: 'g@x',
+ managers: [{ id: 2 }],
+ groups: [{ id: 1 }, { id: 3 }],
+ role: USER_ROLE.GUEST
+ }
+ setGuest(guest as any)
+ const updatedGuest = { ...guest, groups: [{ id: 3 }, { id: 5 }] }
+ setGuest(updatedGuest as any)
+
+ adminQueriesMock.updateUserGroups.mockResolvedValueOnce(undefined)
+
+ const res = await service.updateUserOrGuest(guest.id, { groups: [3, 5] } as UpdateUserDto, USER_ROLE.GUEST)
+ expect(adminQueriesMock.usersQueries.updateUserOrGuest).not.toHaveBeenCalled()
+ expect(adminQueriesMock.updateUserGroups).toHaveBeenCalledWith(guest.id, { add: [5], delete: [1] })
+ expect(adminQueriesMock.updateGuestManagers).not.toHaveBeenCalled()
+ expect(res).toEqual(updatedGuest)
+ })
+
it('validations updateGuest', async () => {
expect(() => service.updateGuest(1, {} as any)).toThrow(/no changes to update/i)
expect(() => service.updateGuest(1, { managers: [] } as any)).toThrow(/guest must have at least one manager/i)
})
+ it('updateUserGroups échoue pour guest', async () => {
+ const guest = { id: 33, login: 'g', email: 'g@x', managers: [{ id: 2 }], groups: [{ id: 1 }], role: USER_ROLE.GUEST }
+ setGuest(guest as any)
+ adminQueriesMock.updateUserGroups.mockRejectedValueOnce(new Error('group error'))
+ await expect(service.updateUserOrGuest(guest.id, { groups: [2] } as any, USER_ROLE.GUEST)).rejects.toThrow('Unable to update user groups')
+ expect(adminQueriesMock.updateGuestManagers).not.toHaveBeenCalled()
+ })
+
it('updateGuestManagers échoue', async () => {
const guest = { id: 33, login: 'g', email: 'g@x', managers: [{ id: 2 }], role: USER_ROLE.GUEST }
setGuest(guest as any)
diff --git a/backend/src/applications/users/services/admin-users-manager.service.ts b/backend/src/applications/users/services/admin-users-manager.service.ts
index 872e5b86..f044c560 100644
--- a/backend/src/applications/users/services/admin-users-manager.service.ts
+++ b/backend/src/applications/users/services/admin-users-manager.service.ts
@@ -62,7 +62,7 @@ export class AdminUsersManager {
tag: this.createUserOrGuest.name,
msg: `${USER_ROLE[userRole]} (${userId}) was created : ${JSON.stringify(anonymizePassword(createUserDto))}`
})
- this.adminQueries.usersQueries.clearWhiteListCaches('*')
+ void this.adminQueries.usersQueries.clearWhiteListCaches('*')
await user.makePaths()
if (userRole <= USER_ROLE.USER) {
return asAdmin ? this.getUser(user.id) : user
@@ -86,6 +86,7 @@ export class AdminUsersManager {
const updateUser: Partial<User> = {}
const updateUserGroups: { add: number[]; delete: number[] } = { add: [], delete: [] }
const updateGuestManagers: { add: number[]; delete: number[] } = { add: [], delete: [] }
+
for (const [k, v] of Object.entries(updateUserDto)) {
switch (k as keyof UpdateUserDto) {
case 'login':
@@ -120,13 +121,13 @@ export class AdminUsersManager {
case 'password':
updateUser.password = await hashPassword(updateUserDto.password)
break
- case 'groups':
- if (userRole === USER_ROLE.USER) {
- const currentGroups: number[] = user.groups?.length ? user.groups.map((g) => g.id) : []
- updateUserGroups.add = v.filter((id: number) => currentGroups.indexOf(id) === -1)
- updateUserGroups.delete = currentGroups.filter((id: number) => v.indexOf(id) === -1)
- }
+ case 'groups': {
+ // allowed for users and guests
+ const currentGroups: number[] = user.groups?.length ? user.groups.map((g) => g.id) : []
+ updateUserGroups.add = v.filter((id: number) => currentGroups.indexOf(id) === -1)
+ updateUserGroups.delete = currentGroups.filter((id: number) => v.indexOf(id) === -1)
break
+ }
case 'managers':
if (userRole === USER_ROLE.GUEST) {
const currentManagers: number[] = user.managers?.length ? user.managers.map((m) => m.id) : []
@@ -138,6 +139,7 @@ export class AdminUsersManager {
updateUser[k] = v
}
}
+
if (Object.keys(updateUser).length) {
// force the type for security reason
const forceRole = userRole === USER_ROLE.GUEST ? USER_ROLE.GUEST : undefined
@@ -145,25 +147,24 @@ export class AdminUsersManager {
throw new HttpException('Unable to update user', HttpStatus.INTERNAL_SERVER_ERROR)
}
}
- if (userRole === USER_ROLE.USER) {
- if (updateUserGroups.add.length || updateUserGroups.delete.length) {
- try {
- await this.adminQueries.updateUserGroups(user.id, updateUserGroups)
- } catch {
- throw new HttpException('Unable to update user groups', HttpStatus.INTERNAL_SERVER_ERROR)
- }
+
+ if (updateUserGroups.add.length || updateUserGroups.delete.length) {
+ try {
+ await this.adminQueries.updateUserGroups(user.id, updateUserGroups)
+ } catch {
+ throw new HttpException('Unable to update user groups', HttpStatus.INTERNAL_SERVER_ERROR)
}
- return this.getUser(userId)
- } else {
- if (updateGuestManagers.add.length || updateGuestManagers.delete.length) {
- try {
- await this.adminQueries.updateGuestManagers(user.id, updateGuestManagers)
- } catch {
- throw new HttpException('Unable to update guest managers', HttpStatus.INTERNAL_SERVER_ERROR)
- }
+ }
+
+ if (userRole === USER_ROLE.GUEST && (updateGuestManagers.add.length || updateGuestManagers.delete.length)) {
+ try {
+ await this.adminQueries.updateGuestManagers(user.id, updateGuestManagers)
+ } catch {
+ throw new HttpException('Unable to update guest managers', HttpStatus.INTERNAL_SERVER_ERROR)
}
- return this.getGuest(userId)
}
+
+ return userRole === USER_ROLE.USER ? this.getUser(userId) : this.getGuest(userId)
}
async deleteUserOrGuest(userId: number, userLogin: string, deleteUserDto: DeleteUserDto): Promise<void> {
@@ -258,7 +259,7 @@ export class AdminUsersManager {
}
// Clear whitelist caches when the group’s visibility is changed
if (updateGroupDto.visibility !== undefined) {
- this.adminQueries.usersQueries.clearWhiteListCaches('*')
+ void this.adminQueries.usersQueries.clearWhiteListCaches('*')
}
return this.adminQueries.groupFromId(groupId)
}
diff --git a/backend/src/applications/users/services/admin-users-queries.service.ts b/backend/src/applications/users/services/admin-users-queries.service.ts
index bce11ccd..0344a674 100644
--- a/backend/src/applications/users/services/admin-users-queries.service.ts
+++ b/backend/src/applications/users/services/admin-users-queries.service.ts
@@ -204,7 +204,7 @@ export class AdminUsersQueries {
groups.add.length
)
this.logger.log({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was added` })
- this.usersQueries.clearWhiteListCaches([userId])
+ void this.usersQueries.clearWhiteListCaches([userId])
} catch (e) {
this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.add)} was not added: ${e}` })
throw new Error('User groups was not added')
@@ -217,7 +217,7 @@ export class AdminUsersQueries {
groups.delete.length
)
this.logger.log({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was deleted` })
- this.usersQueries.clearWhiteListCaches([userId])
+ void this.usersQueries.clearWhiteListCaches([userId])
} catch (e) {
this.logger.error({ tag: this.updateUserGroups.name, msg: `user (${userId}) groups ${JSON.stringify(groups.delete)} was not deleted: ${e}` })
throw new Error('User groups was not deleted')
@@ -273,7 +273,7 @@ export class AdminUsersQueries {
userIdsWithRequiredRole.length
)
this.logger.log({ tag: this.addUsersToGroup.name, msg: `users (${userIds}) was added to group (${groupId})` })
- this.usersQueries.clearWhiteListCaches(userIds)
+ void this.usersQueries.clearWhiteListCaches(userIds)
} catch (e) {
this.logger.error({ tag: this.addUsersToGroup.name, msg: `unable to add users (${userIds}) to group (${groupId}) : ${e}` })
throw new Error('Unable to add users to group')
@@ -310,7 +310,7 @@ export class AdminUsersQueries {
1
)
this.logger.log({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) was removed from group (${groupId})` })
- this.usersQueries.clearWhiteListCaches([userId])
+ void this.usersQueries.clearWhiteListCaches([userId])
} catch (e) {
this.logger.error({ tag: this.removeUserFromGroup.name, msg: `user (${userId}) or group (${groupId}) does not exist : ${e}` })
throw new Error('Unable to remove user from group')
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index f178068e..d2f76d4a 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -11,6 +11,7 @@ import { DB_TOKEN_PROVIDER } from '../../../infrastructure/database/constants'
import * as filesUtilsModule from '../../files/utils/files'
import { fileName, isPathExists } from '../../files/utils/files'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
+import { GROUP_TYPE } from '../constants/group'
import { MEMBER_TYPE } from '../constants/member'
import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ROLE } from '../constants/user'
import { CreateUserDto } from '../dto/create-or-update-user.dto'
@@ -514,21 +515,23 @@ describe(UsersManager.name, () => {
expect(lgSpy).toHaveBeenCalledWith(expect.objectContaining({ msg: expect.stringMatching(/was deleted/) }))
})
- it('guests + proxies', async () => {
+ it('guests list + get', async () => {
usersQueriesService.listGuests = jest.fn().mockResolvedValue([{ id: 1 }])
await expect(usersManager.listGuests(userTest)).resolves.toEqual([{ id: 1 }])
+
const checkSpy = jest.spyOn(adminUsersManager, 'checkUser').mockImplementation(() => undefined)
usersQueriesService.listGuests = jest.fn().mockResolvedValue({ id: 9 })
await expect(usersManager.getGuest(userTest, 9)).resolves.toEqual({ id: 9 })
expect(checkSpy).toHaveBeenCalled()
+ })
+ it('createGuest adds current user as manager only once', async () => {
usersQueriesService.usersWhitelist = jest.fn().mockResolvedValue([userTest.id, 100])
- usersQueriesService.clearWhiteListCaches = jest.fn()
const createSpy = jest.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
+
const dto1: CreateUserDto = { ...userTest, managers: [100], password: 'x' }
const r = await usersManager.createGuest(userTest, dto1)
expect(createSpy).toHaveBeenCalled()
- expect(usersQueriesService.clearWhiteListCaches).toHaveBeenCalledWith([userTest.id])
expect(r).toEqual({ id: 55 })
const args1 = (createSpy as jest.Mock).mock.calls[0][0]
expect(args1.managers).toEqual(expect.arrayContaining([userTest.id]))
@@ -537,9 +540,40 @@ describe(UsersManager.name, () => {
await usersManager.createGuest(userTest, dto2)
const args2 = (createSpy as jest.Mock).mock.calls[0][0]
expect((args2.managers as number[]).filter((m: number) => m === userTest.id)).toHaveLength(1)
+ })
+
+ it('createGuest groups filtering keeps only allowed groups and logs warning', async () => {
+ const warnSpy = jest.spyOn((usersManager as any)['logger'], 'warn').mockImplementation(() => undefined as any)
+ usersQueriesService.usersWhitelist = jest.fn().mockResolvedValue([userTest.id, 100])
+ usersQueriesService.groupsWhitelist = jest.fn().mockResolvedValue([10])
+ const createSpy = jest.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
+ const dto: CreateUserDto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' }
+ await expect(usersManager.createGuest(userTest, dto)).resolves.toEqual({ id: 55 })
+ expect(usersQueriesService.groupsWhitelist).toHaveBeenCalledWith(userTest.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
+ const args = (createSpy as jest.Mock).mock.calls[0][0]
+ expect(args.groups).toEqual([10])
+ expect(warnSpy).toHaveBeenCalledWith(expect.objectContaining({ msg: 'Some groups were not allowed' }))
+ })
+
+ it('createGuest groups keeps all allowed groups without warning', async () => {
+ const warnSpy = jest.spyOn((usersManager as any)['logger'], 'warn').mockImplementation(() => undefined as any)
+ usersQueriesService.usersWhitelist = jest.fn().mockResolvedValue([userTest.id, 100])
+ usersQueriesService.groupsWhitelist = jest.fn().mockResolvedValue([10, 11])
+ const createSpy = jest.spyOn(adminUsersManager, 'createUserOrGuest').mockResolvedValue({ id: 55 } as any)
+
+ const dto: CreateUserDto = { ...userTest, managers: [100], groups: [10, 11], password: 'x' }
+ await expect(usersManager.createGuest(userTest, dto)).resolves.toEqual({ id: 55 })
+ expect(usersQueriesService.groupsWhitelist).toHaveBeenCalledWith(userTest.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
+ const args = (createSpy as jest.Mock).mock.calls[0][0]
+ expect(args.groups).toEqual([10, 11])
+ expect(warnSpy).not.toHaveBeenCalled()
+ })
+
+ it('updateGuest checks ownership and manager whitelist', async () => {
await expect(usersManager.updateGuest(userTest, 9, {} as any)).rejects.toThrow('No changes to update')
usersQueriesService.usersWhitelist = jest.fn().mockResolvedValue([1])
+ usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(true)
await expect(usersManager.updateGuest(userTest, 9, { managers: [2] } as any)).rejects.toThrow('Guest must have at least one manager')
usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(false)
await expect(usersManager.updateGuest(userTest, 9, { email: 'a' } as any)).rejects.toThrow('You are not allowed to do this action')
@@ -554,14 +588,58 @@ describe(UsersManager.name, () => {
await expect(usersManager.updateGuest(userTest, 9, { managers: [userTest.id, 77] } as any)).resolves.toEqual({
managers: [{ id: userTest.id }, { id: 77 }]
})
+ })
+
+ it('updateGuest groups forbidden when current user is not manager', async () => {
+ const updateSpy = jest.spyOn(adminUsersManager, 'updateUserOrGuest')
+ usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(false)
+ usersQueriesService.groupsWhitelist = jest.fn()
+ await expect(usersManager.updateGuest(userTest, 9, { groups: [10] } as any)).rejects.toThrow('You are not allowed to do this action')
+ expect(usersQueriesService.groupsWhitelist).not.toHaveBeenCalled()
+ expect(updateSpy).not.toHaveBeenCalled()
+ })
+ it('updateGuest groups filtering logs warning when some groups are rejected', async () => {
+ const warnSpy = jest.spyOn((usersManager as any)['logger'], 'warn').mockImplementation(() => undefined as any)
+ const updateSpy = jest.spyOn(adminUsersManager, 'updateUserOrGuest')
+ usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(true)
+ usersQueriesService.groupsWhitelist = jest.fn().mockResolvedValue([10])
+ updateSpy.mockResolvedValue({ managers: [{ id: userTest.id }], groups: [{ id: 10 }] } as any)
+
+ await expect(usersManager.updateGuest(userTest, 9, { groups: [10, 11] } as any)).resolves.toEqual({
+ managers: [{ id: userTest.id }],
+ groups: [{ id: 10 }]
+ })
+ expect(usersQueriesService.groupsWhitelist).toHaveBeenCalledWith(userTest.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
+ expect(updateSpy).toHaveBeenLastCalledWith(9, { groups: [10] }, USER_ROLE.GUEST)
+ expect(warnSpy).toHaveBeenCalledWith(expect.objectContaining({ msg: 'Some groups were not allowed' }))
+ })
+
+ it('updateGuest groups does not log warning when all groups are allowed', async () => {
+ const warnSpy = jest.spyOn((usersManager as any)['logger'], 'warn').mockImplementation(() => undefined as any)
+ const updateSpy = jest.spyOn(adminUsersManager, 'updateUserOrGuest')
+ usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(true)
+ usersQueriesService.groupsWhitelist = jest.fn().mockResolvedValue([10, 11])
+ updateSpy.mockResolvedValue({ managers: [{ id: userTest.id }], groups: [{ id: 10 }, { id: 11 }] } as any)
+
+ await expect(usersManager.updateGuest(userTest, 9, { groups: [10, 11] } as any)).resolves.toEqual({
+ managers: [{ id: userTest.id }],
+ groups: [{ id: 10 }, { id: 11 }]
+ })
+ expect(updateSpy).toHaveBeenLastCalledWith(9, { groups: [10, 11] }, USER_ROLE.GUEST)
+ expect(warnSpy).not.toHaveBeenCalled()
+ })
+
+ it('deleteGuest checks ownership then deletes guest', async () => {
usersQueriesService.isGuestManager = jest.fn().mockResolvedValue(null)
await expect(usersManager.deleteGuest(userTest, 9)).rejects.toThrow('You are not allowed to do this action')
usersQueriesService.isGuestManager = jest.fn().mockResolvedValue({ id: 9, login: 'guest' })
const delSpy = jest.spyOn(adminUsersManager, 'deleteUserOrGuest').mockResolvedValue(undefined)
await expect(usersManager.deleteGuest(userTest, 9)).resolves.toBeUndefined()
expect(delSpy).toHaveBeenCalledWith(9, 'guest', { deleteSpace: true, isGuest: true })
+ })
+ it('proxies forward search + online + whitelist', async () => {
usersQueriesService.searchUsersOrGroups = jest.fn().mockResolvedValue([{ id: 1 }])
await expect(usersManager.searchMembers(userTest, { search: '' } as any)).resolves.toEqual([{ id: 1 }])
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index 5c9dd1d0..1e13e217 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -17,6 +17,7 @@ import { configuration, serverConfig } from '../../../configuration/config.envir
import { isPathExists, moveFiles } from '../../files/utils/files'
import { NOTIFICATION_APP, NOTIFICATION_APP_EVENT } from '../../notifications/constants/notifications'
import { NotificationsManager } from '../../notifications/services/notifications-manager.service'
+import { GROUP_TYPE } from '../constants/group'
import { MEMBER_TYPE } from '../constants/member'
import { USER_GROUP_ROLE, USER_MAX_PASSWORD_ATTEMPTS, USER_ONLINE_STATUS, USER_ROLE } from '../constants/user'
import type { UserCreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto'
@@ -339,7 +340,7 @@ export class UsersManager {
const groupId: number = await this.usersQueries.createPersonalGroup(user.id, userCreateOrUpdateGroupDto)
this.logger.log({ tag: this.createPersonalGroup.name, msg: `group (${groupId}) was created : ${JSON.stringify(userCreateOrUpdateGroupDto)}` })
// clear user whitelists
- this.usersQueries.clearWhiteListCaches([user.id])
+ void this.usersQueries.clearWhiteListCaches([user.id])
return this.getGroup(user, groupId, false)
} catch (e) {
this.logger.error({ tag: this.createPersonalGroup.name, msg: `group was not created : ${JSON.stringify(userCreateOrUpdateGroupDto)} : ${e}` })
@@ -467,15 +468,22 @@ export class UsersManager {
}
async createGuest(user: UserModel, createGuestDto: CreateUserDto): Promise<GuestUser> {
- // filter managers that are allowed for current user
+ // only allow managers visible to the current user
const userWhiteList = await this.usersQueries.usersWhitelist(user.id, USER_ROLE.USER)
createGuestDto.managers = createGuestDto.managers.filter((id) => userWhiteList.indexOf(id) > -1)
if (createGuestDto.managers.indexOf(user.id) === -1) {
// force user as manager during creation
createGuestDto.managers.push(user.id)
}
- // clear user whitelists
- this.usersQueries.clearWhiteListCaches([user.id])
+ if (createGuestDto?.groups?.length) {
+ // only allow personal groups where the current user is a manager
+ const groupWhiteList = await this.usersQueries.groupsWhitelist(user.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
+ const nbGroups = createGuestDto.groups.length
+ createGuestDto.groups = createGuestDto.groups.filter((id) => groupWhiteList.indexOf(id) > -1)
+ if (nbGroups !== createGuestDto.groups.length) {
+ this.logger.warn({ tag: this.createGuest.name, msg: 'Some groups were not allowed' })
+ }
+ }
return this.adminUsersManager.createUserOrGuest(createGuestDto, USER_ROLE.GUEST, true)
}
@@ -483,16 +491,25 @@ export class UsersManager {
if (!Object.keys(updateGuestDto).length) {
throw new HttpException('No changes to update', HttpStatus.BAD_REQUEST)
}
+ if (!(await this.usersQueries.isGuestManager(user.id, guestId))) {
+ throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
+ }
if (updateGuestDto.managers) {
- // filter managers that are allowed for current user
+ // only allow managers visible to the current user
const userWhiteList = await this.usersQueries.usersWhitelist(user.id, USER_ROLE.USER)
updateGuestDto.managers = updateGuestDto.managers.filter((id) => userWhiteList.indexOf(id) > -1)
if (!updateGuestDto.managers.length) {
throw new HttpException('Guest must have at least one manager', HttpStatus.BAD_REQUEST)
}
}
- if (!(await this.usersQueries.isGuestManager(user.id, guestId))) {
- throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
+ if (updateGuestDto.groups) {
+ // only allow personal groups where the current user is a manager
+ const groupWhiteList = await this.usersQueries.groupsWhitelist(user.id, GROUP_TYPE.PERSONAL, USER_GROUP_ROLE.MANAGER)
+ const nbGroups = updateGuestDto.groups.length
+ updateGuestDto.groups = updateGuestDto.groups.filter((id) => groupWhiteList.indexOf(id) > -1)
+ if (nbGroups !== updateGuestDto.groups.length) {
+ this.logger.warn({ tag: this.updateGuest.name, msg: 'Some groups were not allowed' })
+ }
}
const guest = await this.adminUsersManager.updateUserOrGuest(guestId, updateGuestDto, USER_ROLE.GUEST)
return guest.managers.find((m) => m.id === user.id) ? guest : null
diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.ts
index d3ec8202..3d8b545e 100644
--- a/backend/src/applications/users/services/users-queries.service.ts
+++ b/backend/src/applications/users/services/users-queries.service.ts
@@ -148,7 +148,7 @@ export class UsersQueries {
async createUserOrGuest(createUserDto: CreateUserDto, userRole: USER_ROLE): Promise<User['id']> {
const userId: number = dbGetInsertedId(await this.db.insert(users).values({ ...createUserDto, role: userRole } as User))
- if (userRole === USER_ROLE.USER && createUserDto.groups?.length) {
+ if (createUserDto.groups?.length) {
await this.db.insert(usersGroups).values(createUserDto.groups.map((gid: number) => ({ userId: userId, groupId: gid })))
}
if (userRole === USER_ROLE.GUEST && createUserDto.managers?.length) {
@@ -182,6 +182,7 @@ export class UsersQueries {
}
async searchUsersOrGroups(searchMembersDto: SearchMembersDto, userId?: number): Promise<Member[]> {
+ // `userId` is required for user routes to avoid searching across all users and groups
const limit = searchMembersDto.onlyUsers || searchMembersDto.onlyGroups ? 6 : 3
const members: Member[] = []
if (!searchMembersDto.onlyGroups) {
@@ -381,7 +382,7 @@ export class UsersQueries {
try {
await this.db.insert(usersGroups).values(members.add.map((m) => ({ userId: m.id, groupId: groupId, role: m.groupRole })))
// clear cache
- this.clearWhiteListCaches(members.add.map((m) => m.id))
+ void this.clearWhiteListCaches(members.add.map((m) => m.id))
this.logger.log({
tag: this.updateGroupMembers.name,
msg: `users ${JSON.stringify(members.add.map((m) => m.id))} was added to group (${groupId})`
@@ -401,7 +402,7 @@ export class UsersQueries {
.where(and(eq(usersGroups.groupId, groupId), inArray(usersGroups.userId, members.remove)))
.limit(members.remove.length)
// clear cache
- this.clearWhiteListCaches(members.remove)
+ void this.clearWhiteListCaches(members.remove)
this.logger.log({ tag: this.updateGroupMembers.name, msg: `users ${JSON.stringify(members.remove)} was removed from group (${groupId})` })
} catch (e) {
this.logger.error({
@@ -419,7 +420,7 @@ export class UsersQueries {
const where: SQL[] = [...(guestId ? [eq(usersGuests.guestId, guestId)] : []), ...(asAdmin ? [] : [eq(usersGuests.userId, managerId)])]
const managersGuestAlias: any = alias(usersGuests, 'managersGuestAlias')
const managersAlias: any = alias(users, 'managersAlias')
- const guests = await this.db
+ const q = this.db
.select({
id: users.id,
login: users.login,
@@ -444,15 +445,30 @@ export class UsersQueries {
type: sql.raw(`'${MEMBER_TYPE.USER}'`),
description: managersAlias.email,
createdAt: dateTimeUTC(managersGuestAlias.createdAt)
- } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'createdAt'>, any>)
+ } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'login' | 'description' | 'type' | 'createdAt'>, any>),
+ ...(guestId && {
+ groups: concatDistinctObjectsInArray(groups.id, {
+ id: groups.id,
+ name: groups.name,
+ description: groups.description,
+ type: sql.raw(`'${MEMBER_TYPE.PGROUP}'`),
+ permissions: groups.permissions,
+ createdAt: dateTimeUTC(usersGroups.createdAt)
+ } satisfies Record<keyof Pick<Member, 'id' | 'name' | 'description' | 'type' | 'permissions' | 'createdAt'>, any>)
+ })
} satisfies GuestUser | SelectedFields<any, any>)
.from(usersGuests)
- .innerJoin(users, and(eq(users.id, usersGuests.guestId), eq(users.role, USER_ROLE.GUEST)))
- .leftJoin(managersGuestAlias, eq(managersGuestAlias.guestId, users.id))
- .leftJoin(managersAlias, eq(managersAlias.id, managersGuestAlias.userId))
- .where(and(...where))
- .groupBy(users.id)
- .limit(guestId ? 1 : undefined)
+ q.innerJoin(users, and(eq(users.id, usersGuests.guestId), eq(users.role, USER_ROLE.GUEST)))
+ q.leftJoin(managersGuestAlias, eq(managersGuestAlias.guestId, users.id))
+ q.leftJoin(managersAlias, eq(managersAlias.id, managersGuestAlias.userId))
+ if (guestId) {
+ q.leftJoin(usersGroups, eq(usersGroups.userId, users.id))
+ q.leftJoin(groups, and(eq(groups.id, usersGroups.groupId), eq(groups.type, GROUP_TYPE.PERSONAL)))
+ }
+ q.where(and(...where))
+ q.groupBy(users.id)
+ q.limit(guestId ? 1 : undefined)
+ const guests = await q
return guestId ? guests[0] : guests
}
@@ -533,19 +549,24 @@ export class UsersQueries {
}
@CacheDecorator(900)
- async groupsWhitelist(userId: number): Promise<number[]> {
+ async groupsWhitelist(userId: number, groupType?: GROUP_TYPE, userGroupRole?: USER_GROUP_ROLE): Promise<number[]> {
/* Get the list of group IDs the current user is allowed to see.
- A group marked VISIBLE is always included.
- A group marked ISOLATED is always excluded.
- A PRIVATE group is included only if the user is a direct member of it.
- Visibility does not inherit from parent or child groups.
*/
+ const optionalFilters: SQL[] = [
+ ...(groupType != null ? [eq(groups.type, groupType)] : []),
+ ...(userGroupRole != null ? [eq(usersGroups.role, userGroupRole)] : [])
+ ]
const q = this.db
.select({ id: sql`JSON_ARRAYAGG(${groups.id}) as ids` })
.from(groups)
.leftJoin(usersGroups, and(eq(usersGroups.groupId, groups.id), eq(usersGroups.userId, userId)))
.where(
and(
+ ...optionalFilters,
ne(groups.visibility, GROUP_VISIBILITY.ISOLATED),
or(eq(groups.visibility, GROUP_VISIBILITY.VISIBLE), and(eq(groups.visibility, GROUP_VISIBILITY.PRIVATE), isNotNull(usersGroups.userId)))
)
@@ -554,29 +575,30 @@ export class UsersQueries {
return JSON.parse(r[0].ids) || []
}
- clearWhiteListCaches(userIds: number[] | '*') {
- // '*' -> Means all entries
- const whitelists = [this.usersWhitelist.name, this.groupsWhitelist.name]
- const keysPromise =
- userIds === '*'
- ? Promise.all(whitelists.map((whitelist) => this.cache.keys(this.cache.genSlugKey(this.constructor.name, whitelist, userIds)))).then(
- (keyLists: string[][]) => keyLists.flat()
- )
- : Promise.resolve(
- whitelists.flatMap((whitelist) =>
- userIds.flatMap((id) => [
- this.cache.genSlugKey(this.constructor.name, whitelist, id),
- this.cache.genSlugKey(this.constructor.name, whitelist, id, '*')
- ])
- )
- )
- keysPromise
- .then((keys: string[]) => {
- if (!keys.length) return
- this.logger.verbose({ tag: this.clearWhiteListCaches.name, msg: JSON.stringify(keys) })
- return this.cache.mdel(keys)
- })
- .catch((e: Error) => this.logger.error({ tag: this.clearWhiteListCaches.name, msg: `${e}` }))
+ async clearWhiteListCaches(userIds: number[] | '*'): Promise<void> {
+ try {
+ // '*' -> Means all entries
+ const whitelists = [this.usersWhitelist.name, this.groupsWhitelist.name]
+ const keysToDelete: string[] = []
+ if (userIds === '*') {
+ const patterns = whitelists.map((whitelist) => this.cache.genSlugKey(this.constructor.name, whitelist, userIds))
+ for (const pattern of patterns) {
+ keysToDelete.push(...(await this.cache.keys(pattern)))
+ }
+ } else {
+ // exact keys for 1-arg cache calls
+ keysToDelete.push(...whitelists.flatMap((whitelist) => userIds.map((id) => this.cache.genSlugKey(this.constructor.name, whitelist, id))))
+ // dynamic keys for optional-args cache calls
+ const patterns = whitelists.flatMap((whitelist) => userIds.map((id) => this.cache.genSlugKey(this.constructor.name, whitelist, id, '*')))
+ for (const pattern of patterns) {
+ keysToDelete.push(...(await this.cache.keys(pattern)))
+ }
+ }
+ this.logger.verbose({ tag: this.clearWhiteListCaches.name, msg: JSON.stringify(keysToDelete) })
+ await this.cache.mdel(keysToDelete)
+ } catch (e) {
+ this.logger.error({ tag: this.clearWhiteListCaches.name, msg: `${e}` })
+ }
}
async allUserIdsFromGroupsAndSubGroups(groupIds: number[]): Promise<number[]> {
@@ -608,7 +630,8 @@ export class UsersQueries {
/* Search for groups */
const where: SQL[] = [like(groups.name, `%${searchMembersDto.search}%`)]
if (userId) {
- let idsWhitelist: number[] = await this.groupsWhitelist(userId)
+ const userRole = searchMembersDto.isGroupManager ? USER_GROUP_ROLE.MANAGER : undefined
+ let idsWhitelist: number[] = await this.groupsWhitelist(userId, undefined, userRole)
if (searchMembersDto.ignoreGroupIds?.length) {
idsWhitelist = idsWhitelist.filter((id) => searchMembersDto.ignoreGroupIds.indexOf(id) === -1)
}
@@ -616,9 +639,13 @@ export class UsersQueries {
} else if (searchMembersDto.ignoreGroupIds?.length) {
where.unshift(notInArray(groups.id, searchMembersDto.ignoreGroupIds))
}
+
if (searchMembersDto.excludePersonalGroups) {
where.unshift(eq(groups.type, GROUP_TYPE.USER))
+ } else if (searchMembersDto.onlyPersonalGroups) {
+ where.unshift(eq(groups.type, GROUP_TYPE.PERSONAL))
}
+
return this.db
.select({ id: groups.id, name: groups.name, description: groups.description, type: groups.type, permissions: groups.permissions })
.from(groups)
diff --git a/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts b/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
index cb864044..e0871274 100644
--- a/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
+++ b/frontend/src/app/applications/admin/components/dialogs/admin-guest-dialog.component.ts
@@ -48,7 +48,7 @@ export class AdminGuestDialogComponent extends UserGuestDialogComponent {
super()
}
- override searchMembers(query: string): Observable<MemberModel[]> {
+ override searchManagers(query: string): Observable<MemberModel[]> {
const search: SearchMembersDto = {
search: query,
ignoreUserIds: this.guestForm.value.managers.map((m: MemberModel) => m.id),
@@ -58,6 +58,16 @@ export class AdminGuestDialogComponent extends UserGuestDialogComponent {
return this.adminService.searchMembers(search)
}
+ override searchGroups(query: string): Observable<MemberModel[]> {
+ const search: SearchMembersDto = {
+ search: query,
+ onlyGroups: true,
+ onlyPersonalGroups: true,
+ ignoreGroupIds: this.guestForm.value.groups.map((m: MemberModel) => m.id)
+ }
+ return this.adminService.searchMembers(search)
+ }
+
override async onSubmit() {
this.submitted = true
if (this.confirmDeletion) {
diff --git a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html
index 2c866146..41259d05 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html
+++ b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.html
@@ -20,6 +20,7 @@
</div>
<div class="modal-body" [formGroup]="guestForm">
<tabset [justified]="true" type="pills">
+
<tab (selectTab)="tabView=null" customClass="tab-dialog form-validation">
<ng-template tabHeading>
<span class="app-tab-heading">
@@ -178,6 +179,7 @@
</div>
</div>
</tab>
+
<tab (selectTab)="tabView='managers'" customClass="tab-dialog">
<ng-template tabHeading>
<span class="app-tab-heading">
@@ -192,13 +194,32 @@
(membersChange)="updateManagers($event)"
[withPermissions]="false"
[customPlaceholder]="'Type to search for managers to add'"
- [searchFunction]="searchMembers.bind(this)">
+ [searchFunction]="searchManagers.bind(this)">
</app-user-search>
@if (!guestForm.value.managers.length) {
<small class="text-danger" l10nTranslate>At least one manager is required</small>
}
</div>
</tab>
+
+ <tab (selectTab)="tabView='groups'" customClass="tab-dialog">
+ <ng-template tabHeading>
+ <span class="app-tab-heading">
+ <fa-icon [icon]="icons.faUsers"></fa-icon>
+ <span class="app-tab-label" l10nTranslate>Groups</span>
+ <span class="app-tab-count">{{ guestForm.value.groups.length || 0 }}</span>
+ </span>
+ </ng-template>
+ <div class="app-tab-content my-3">
+ <app-user-search
+ [members]="guestForm.value.groups"
+ (membersChange)="updateGroups($event)"
+ [withPermissions]="false"
+ [customPlaceholder]="'Type to search for groups to add'"
+ [searchFunction]="searchGroups.bind(this)">
+ </app-user-search>
+ </div>
+ </tab>
</tabset>
</div>
<div class="modal-footer">
diff --git a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.ts b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.ts
index 1e08b522..ff20afa2 100644
--- a/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.ts
+++ b/frontend/src/app/applications/users/components/dialogs/user-guest-dialog.component.ts
@@ -61,7 +61,7 @@ export class UserGuestDialogComponent implements OnInit {
protected submitted = false
protected loading = false
protected confirmDeletion = false
- protected tabView: undefined | 'managers'
+ protected tabView: undefined | 'managers' | 'groups'
// form
protected guestForm: FormGroup<{
login: FormControl<string>
@@ -73,6 +73,7 @@ export class UserGuestDialogComponent implements OnInit {
notification: FormControl<number>
isActive: FormControl<boolean>
managers: FormControl<MemberModel[]>
+ groups: FormControl<MemberModel[]>
}>
protected readonly i18nLanguageText = i18nLanguageText
@@ -88,7 +89,8 @@ export class UserGuestDialogComponent implements OnInit {
this.guest?.notification || Object.values(USER_NOTIFICATION_TEXT).indexOf(USER_NOTIFICATION_TEXT.APPLICATION_EMAIL)
),
isActive: new FormControl<boolean>(this.guest ? this.guest.isActive : true),
- managers: new FormControl<MemberModel[]>(this.guest?.managers || [ownerToMember(this.user)])
+ managers: new FormControl<MemberModel[]>(this.guest?.managers || [ownerToMember(this.user)]),
+ groups: new FormControl<MemberModel[]>(this.guest?.groups || [])
})
}
@@ -103,7 +105,7 @@ export class UserGuestDialogComponent implements OnInit {
this.guestForm.controls.managers.setErrors(managers.length ? null : { incorrect: true })
}
- searchMembers(query: string): Observable<MemberModel[]> {
+ searchManagers(query: string): Observable<MemberModel[]> {
const search: SearchMembersDto = {
search: query,
ignoreUserIds: this.guestForm.value.managers.map((m: MemberModel) => m.id),
@@ -113,6 +115,22 @@ export class UserGuestDialogComponent implements OnInit {
return this.userService.searchMembers(search)
}
+ searchGroups(query: string): Observable<MemberModel[]> {
+ const search: SearchMembersDto = {
+ search: query,
+ onlyGroups: true,
+ onlyPersonalGroups: true,
+ isGroupManager: true,
+ ignoreGroupIds: this.guestForm.value.groups.map((m: MemberModel) => m.id)
+ }
+ return this.userService.searchMembers(search)
+ }
+
+ updateGroups(groups: MemberModel[]) {
+ this.guestForm.controls.groups.setValue(groups)
+ this.guestForm.controls.groups.markAsDirty()
+ }
+
onCancel() {
if (this.confirmDeletion) {
this.confirmDeletion = false
@@ -167,9 +185,7 @@ export class UserGuestDialogComponent implements OnInit {
}
protected makeDto(create: true): CreateUserDto
-
protected makeDto(create?: false): UpdateUserDto
-
protected makeDto(create = false): CreateUserDto | UpdateUserDto {
let dto = {}
if (create) {
@@ -186,6 +202,7 @@ export class UserGuestDialogComponent implements OnInit {
case 'language':
dto[k] = dto[k] === USER_LANGUAGE_AUTO ? null : dto[k]
break
+ case 'groups':
case 'managers':
dto[k] = dto[k].map((m: MemberModel) => m.id)
break
diff --git a/frontend/src/app/applications/users/models/guest.model.ts b/frontend/src/app/applications/users/models/guest.model.ts
index d916120a..5d76e79e 100644
--- a/frontend/src/app/applications/users/models/guest.model.ts
+++ b/frontend/src/app/applications/users/models/guest.model.ts
@@ -1,4 +1,4 @@
-import { GuestUser } from '@sync-in-server/backend/src/applications/users/interfaces/guest-user.interface'
+import type { GuestUser } from '@sync-in-server/backend/src/applications/users/interfaces/guest-user.interface'
import { getNewly } from '../../../common/utils/functions'
import { dJs } from '../../../common/utils/time'
import { userAvatarUrl } from '../user.functions'
@@ -22,6 +22,7 @@ export class GuestUserModel implements GuestUser {
lastIp: string
createdAt: Date
managers: MemberModel[]
+ groups: MemberModel[]
// extra properties
userIsActiveText: string
@@ -34,6 +35,7 @@ export class GuestUserModel implements GuestUser {
constructor(guest: GuestUser) {
this.setManagers(guest)
+ this.setGroups(guest)
Object.assign(this, guest)
this.avatarUrl = userAvatarUrl(guest.login)
this.userIsActiveText = this.isActive ? 'active' : 'suspended'
@@ -46,4 +48,10 @@ export class GuestUserModel implements GuestUser {
guest.managers = guest.managers.map((g) => new MemberModel(g))
}
}
+
+ private setGroups(guest: GuestUser) {
+ if (guest?.groups) {
+ guest.groups = guest.groups.map((g) => new MemberModel(g))
+ }
+ }
}