Skip to content

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

19.3 KB
Raw Blame
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { FastifyReply } from 'fastify'
import { AuthManager } from '../../../authentication/auth.service.js'
import { LoginResponseDto } from '../../../authentication/dto/login-response.dto.js'
import { toErrorMessage } from '../../../common/errors.js'
import { anonymizePassword, hashPassword } from '../../../common/functions.js'
import { isPathExists, moveFiles, removeFiles } from '../../files/utils/files.js'
import { GROUP_TYPE } from '../constants/group.js'
import { USER_NOTIFICATION, USER_ROLE } from '../constants/user.js'
import type { CreateOrUpdateGroupDto } from '../dto/create-or-update-group.dto.js'
import type { CreateUserDto, UpdateUserDto, UpdateUserFromGroupDto } from '../dto/create-or-update-user.dto.js'
import type { DeleteUserDto } from '../dto/delete-user.dto.js'
import type { ValidatedSearchMembersDto } from '../dto/search-members.dto.js'
import type { AdminGroup } from '../interfaces/admin-group.interface.js'
import type { AdminUser } from '../interfaces/admin-user.interface.js'
import type { GroupBrowse } from '../interfaces/group-browse.interface.js'
import type { GuestUser } from '../interfaces/guest-user.interface.js'
import type { Member } from '../interfaces/member.interface.js'
import { UserModel } from '../models/user.model.js'
import type { User } from '../schemas/user.interface.js'
import { isValidUserLogin } from '../utils/login.js'
import { AdminUsersQueries } from './admin-users-queries.service.js'
import { FilesQuotaManager } from '../../files/services/files-quota-manager.service.js'
import { FILE_REPOSITORY } from '../../files/constants/operations.js'

@Injectable()
export class AdminUsersManager {
  private readonly logger = new Logger(AdminUsersManager.name)

  constructor(
    private readonly authManager: AuthManager,
    private readonly filesQuotaManager: FilesQuotaManager,
    private readonly adminQueries: AdminUsersQueries
  ) {}

  listUsers(): Promise<AdminUser[]> {
    return this.adminQueries.listUsers()
  }

  async getUser(userId: number): Promise<AdminUser> {
    const user = await this.adminQueries.listUsers(userId)
    this.checkUser(user, true)
    return user
  }

  async getGuest(guestId: number): Promise<GuestUser> {
    const user = await this.adminQueries.usersQueries.listGuests(guestId, 0, true)
    this.checkUser(user, true)
    return user
  }

  async createUserOrGuest(createUserDto: CreateUserDto, userRole: USER_ROLE.GUEST, asAdmin: boolean): Promise<GuestUser>
  async createUserOrGuest(createUserDto: CreateUserDto, userRole: USER_ROLE, asAdmin: true): Promise<AdminUser | GuestUser>
  async createUserOrGuest(createUserDto: CreateUserDto, userRole: USER_ROLE, asAdmin?: false): Promise<UserModel>
  async createUserOrGuest(
    createUserDto: CreateUserDto,
    userRole: USER_ROLE = USER_ROLE.USER,
    asAdmin = false
  ): Promise<UserModel | AdminUser | GuestUser> {
    this.validateUserLogin(createUserDto.login)
    await this.loginOrEmailAlreadyUsed(createUserDto.login, createUserDto.email)
    try {
      createUserDto.password = await hashPassword(createUserDto.password)
      const userId: number = await this.adminQueries.usersQueries.createUserOrGuest(createUserDto, userRole)
      const { groups: _groups, managers: _managers, ...userProperties } = createUserDto
      const user = new UserModel({
        ...userProperties,
        id: userId,
        role: userRole,
        isActive: userProperties.isActive ?? true,
        notification: userProperties.notification ?? USER_NOTIFICATION.APPLICATION_EMAIL,
        permissions: userProperties.permissions ?? ''
      })
      this.logger.log({
        tag: this.createUserOrGuest.name,
        msg: `${USER_ROLE[userRole]} (${userId}) was created : ${JSON.stringify(anonymizePassword(createUserDto))}`
      })
      void this.adminQueries.usersQueries.clearWhiteListCaches('*')
      await user.makePaths()
      if (userRole <= USER_ROLE.USER) {
        return asAdmin ? this.getUser(user.id) : user
      } else {
        return asAdmin ? this.getGuest(user.id) : user
      }
    } catch (e) {
      this.logger.error({ tag: this.createUserOrGuest.name, msg: `unable to create user *${createUserDto.login}* : ${toErrorMessage(e)}` })
      throw new HttpException('Unable to create user', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  async updateUserOrGuest(userId: number, updateUserDto: UpdateUserDto): Promise<AdminUser>
  async updateUserOrGuest(userId: number, updateUserDto: UpdateUserDto, userRole: USER_ROLE.GUEST): Promise<GuestUser>
  async updateUserOrGuest(
    userId: number,
    updateUserDto: UpdateUserDto,
    userRole: USER_ROLE.USER | USER_ROLE.GUEST = USER_ROLE.USER
  ): Promise<AdminUser | GuestUser> {
    const user: AdminUser & GuestUser = userRole === USER_ROLE.USER ? await this.getUser(userId) : await this.getGuest(userId)
    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) as { [K in keyof UpdateUserDto]-?: [K, UpdateUserDto[K]] }[keyof UpdateUserDto][]) {
      switch (k) {
        case 'login':
          if (user.login === v) {
            break
          }
          this.validateUserLogin(v as string)
          if (await this.adminQueries.usersQueries.checkUserExists(v as string)) {
            throw new HttpException('Login already used', HttpStatus.FORBIDDEN)
          }
          if (userRole === USER_ROLE.USER || userRole === USER_ROLE.GUEST) {
            if (!(await this.renameUserSpace(user.login, v as string))) {
              throw new HttpException('Unable to rename user space', HttpStatus.INTERNAL_SERVER_ERROR)
            }
          }
          updateUser.login = v as string
          break
        case 'email':
          if (user.email === v) {
            break
          }
          if (await this.adminQueries.usersQueries.checkUserExists(null, v as string)) {
            throw new HttpException('Email already used', HttpStatus.FORBIDDEN)
          }
          updateUser.email = v as string
          break
        case 'isActive':
          updateUser.isActive = v as boolean
          if (v) {
            updateUser.passwordAttempts = 0
          }
          break
        case 'password':
          updateUser.password = await hashPassword(updateUserDto.password!)
          break
        case 'groups': {
          // allowed for users and guests
          const currentGroups: number[] = user.groups?.length ? user.groups.map((g) => g.id) : []
          updateUserGroups.add = (v as number[]).filter((id: number) => currentGroups.indexOf(id) === -1)
          updateUserGroups.delete = currentGroups.filter((id: number) => (v as number[]).indexOf(id) === -1)
          break
        }
        case 'managers':
          if (userRole === USER_ROLE.GUEST) {
            const currentManagers: number[] = user.managers?.length ? user.managers.map((m) => m.id) : []
            updateGuestManagers.add = (v as number[]).filter((id: number) => currentManagers.indexOf(id) === -1)
            updateGuestManagers.delete = currentManagers.filter((id: number) => (v as number[]).indexOf(id) === -1)
          }
          break
        default:
          Object.assign(updateUser, { [k]: v })
      }
    }

    if (Object.keys(updateUser).length) {
      // force the type for security reason
      const forceRole = userRole === USER_ROLE.GUEST ? USER_ROLE.GUEST : undefined
      // updates in db
      if (!(await this.adminQueries.usersQueries.updateUserOrGuest(user.id, updateUser, forceRole))) {
        throw new HttpException('Unable to update user', HttpStatus.INTERNAL_SERVER_ERROR)
      }
      // update quota in cache
      if ('storageQuota' in updateUser) {
        void this.filesQuotaManager.updateStorageQuota(user.id, FILE_REPOSITORY.USER, updateUser.storageQuota as number | null)
      }
    }

    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 (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 userRole === USER_ROLE.USER ? this.getUser(userId) : this.getGuest(userId)
  }

  async deleteUserOrGuest(userId: number, userLogin: string, deleteUserDto: DeleteUserDto): Promise<void> {
    try {
      const deleted = await this.adminQueries.deleteUser(userId, userLogin)
      await this.adminQueries.usersQueries.clearWebDAVAuthCache(userId)
      if (deleted) {
        this.logger.log({ tag: this.deleteUserOrGuest.name, msg: `*${userLogin}* (${userId}) was deleted` })
      } else {
        this.logger.error({ tag: this.deleteUserOrGuest.name, msg: `*${userLogin}* (${userId}) was not deleted : not found` })
      }
      if (deleteUserDto.deleteSpace) {
        await this.deleteUserSpace(userLogin)
      }
    } catch (e) {
      this.logger.error({ tag: this.deleteUserOrGuest.name, msg: `unable to delete *${userLogin}* (${userId}) : ${toErrorMessage(e)}` })
      throw new HttpException('Unable to delete user', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  async deleteUserFromAdmin(userId: number, deleteUserDto: DeleteUserDto): Promise<void> {
    const userToDelete: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(userId))
    if (!userToDelete.isUser) {
      throw new HttpException('User mismatch', HttpStatus.BAD_REQUEST)
    }
    await this.deleteUserOrGuest(userToDelete.id, userToDelete.login, deleteUserDto)
  }

  async deleteGuestFromAdmin(guestId: number): Promise<void> {
    const guestToDelete: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(guestId))
    if (!guestToDelete.isGuest) {
      throw new HttpException('User mismatch', HttpStatus.BAD_REQUEST)
    }
    await this.deleteUserOrGuest(guestToDelete.id, guestToDelete.login, { deleteSpace: true })
  }

  listGuests(): Promise<GuestUser[]> {
    return this.adminQueries.usersQueries.listGuests(null, null, true)
  }

  createGuest(user: UserModel, createGuestDto: CreateUserDto): Promise<GuestUser> {
    createGuestDto.managers ??= []
    if (!createGuestDto.managers.length) {
      createGuestDto.managers.push(user.id)
    }
    return this.createUserOrGuest(createGuestDto, USER_ROLE.GUEST, true)
  }

  updateGuest(guestId: number, updateGuestDto: UpdateUserDto): Promise<GuestUser> {
    if (!Object.keys(updateGuestDto).length) {
      throw new HttpException('No changes to update', HttpStatus.BAD_REQUEST)
    }
    if (updateGuestDto.managers && !updateGuestDto.managers.length) {
      throw new HttpException('Guest must have at least one manager', HttpStatus.BAD_REQUEST)
    }
    return this.updateUserOrGuest(guestId, updateGuestDto, USER_ROLE.GUEST)
  }

  async browseGroups(name?: string, type: GROUP_TYPE = GROUP_TYPE.USER): Promise<GroupBrowse> {
    if (name) {
      const group = await this.adminQueries.groupFromName(name)
      if (!group) {
        throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
      }
      return { parentGroup: group, members: await this.adminQueries.browseGroupMembers(group.id, type) }
    }
    return { parentGroup: undefined, members: await this.adminQueries.browseRootGroupMembers(type) }
  }

  async getGroup(groupId: number): Promise<AdminGroup> {
    const group = await this.adminQueries.groupFromId(groupId)
    if (!group) {
      throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
    }
    return group
  }

  async createGroup(createGroupDto: CreateOrUpdateGroupDto): Promise<AdminGroup> {
    if (!createGroupDto.name) {
      this.logger.error({ tag: this.createGroup.name, msg: `missing group name : ${JSON.stringify(createGroupDto)}` })
      throw new HttpException('Group name is missing', HttpStatus.BAD_REQUEST)
    }
    await this.checkGroupNameExists(createGroupDto.name)
    try {
      const groupId: number = await this.adminQueries.createGroup(createGroupDto)
      this.logger.log({ tag: this.createGroup.name, msg: `group (${groupId}) was created : ${JSON.stringify(createGroupDto)}` })
      return this.getGroup(groupId)
    } catch (e) {
      this.logger.error({ tag: this.createGroup.name, msg: `group was not created : ${JSON.stringify(createGroupDto)} : ${toErrorMessage(e)}` })
      throw new HttpException('Unable to create group', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  async updateGroup(groupId: number, updateGroupDto: CreateOrUpdateGroupDto): Promise<AdminGroup> {
    if (updateGroupDto.name) {
      await this.checkGroupNameExists(updateGroupDto.name)
    }
    const affectedUserIds =
      updateGroupDto.permissions !== undefined ? await this.adminQueries.usersQueries.allUserIdsFromGroupsAndSubGroups([groupId]) : []
    if (!(await this.adminQueries.updateGroup(groupId, updateGroupDto))) {
      throw new HttpException('Unable to update group', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    if (affectedUserIds.length) {
      await this.adminQueries.usersQueries.clearWebDAVAuthCache(affectedUserIds)
    }
    // Clear whitelist caches when the group’s visibility is changed
    if (updateGroupDto.visibility !== undefined) {
      void this.adminQueries.usersQueries.clearWhiteListCaches('*')
    }
    return this.getGroup(groupId)
  }

  async deleteGroup(groupId: number): Promise<void> {
    const affectedUserIds = await this.adminQueries.usersQueries.allUserIdsFromGroupsAndSubGroups([groupId])
    if (await this.adminQueries.deleteGroup(groupId)) {
      if (affectedUserIds.length) {
        await this.adminQueries.usersQueries.clearWebDAVAuthCache(affectedUserIds)
      }
      this.logger.log({ tag: this.deleteGroup.name, msg: `group (${groupId}) was deleted` })
    } else {
      this.logger.warn({ tag: this.deleteGroup.name, msg: `group (${groupId}) does not exist` })
      throw new HttpException('Unable to delete group', HttpStatus.BAD_REQUEST)
    }
  }

  async addUsersToGroup(groupId: number, userIds: number[]): Promise<void> {
    const group = await this.adminQueries.groupFromId(groupId)
    if (!group) {
      throw new HttpException('Group not found', HttpStatus.NOT_FOUND)
    }
    try {
      await this.adminQueries.addUsersToGroup(groupId, userIds, group.type === GROUP_TYPE.USER ? USER_ROLE.USER : undefined)
    } catch (e) {
      throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
    }
  }

  async updateUserFromGroup(groupId: number, userId: number, updateUserFromGroupDto: UpdateUserFromGroupDto): Promise<void> {
    try {
      await this.adminQueries.updateUserFromGroup(groupId, userId, updateUserFromGroupDto.role)
    } catch (e) {
      throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
    }
  }

  async removeUserFromGroup(groupId: number, userId: number): Promise<void> {
    try {
      await this.adminQueries.removeUserFromGroup(groupId, userId)
    } catch (e) {
      throw new HttpException(toErrorMessage(e), HttpStatus.BAD_REQUEST)
    }
  }

  searchMembers(searchMembersDto: ValidatedSearchMembersDto): Promise<Member[]> {
    return this.adminQueries.usersQueries.searchUsersOrGroups(searchMembersDto)
  }

  async impersonateUser(admin: UserModel, userId: number, res: FastifyReply): Promise<LoginResponseDto> {
    if (admin.id === userId) {
      throw new HttpException('You are already logged in', HttpStatus.BAD_REQUEST)
    }
    const user: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(userId))
    user.impersonatedFromId = admin.id
    user.impersonatedClientId = admin.clientId
    return this.authManager.setCookies(user, res)
  }

  async logoutImpersonateUser(user: UserModel, res: FastifyReply): Promise<LoginResponseDto> {
    if (!user.impersonatedFromId) {
      throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
    }
    const admin: UserModel = this.checkUser(await this.adminQueries.usersQueries.from(user.impersonatedFromId))
    if (!admin.isAdmin) {
      throw new HttpException('You are not allowed to do this action', HttpStatus.FORBIDDEN)
    }
    admin.clientId = user.impersonatedClientId
    return this.authManager.setCookies(admin, res)
  }

  async deleteUserSpace(userLogin: string): Promise<void> {
    const userSpace: string = UserModel.getHomePath(userLogin)
    try {
      if (await isPathExists(userSpace)) {
        await removeFiles(userSpace)
        this.logger.log({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* was deleted` })
      } else {
        this.logger.warn({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* does not exist : ${userSpace}` })
      }
    } catch (e) {
      this.logger.warn({ tag: this.deleteUserSpace.name, msg: `user space *${userLogin}* (${userSpace}) was not deleted : ${toErrorMessage(e)}` })
      throw new HttpException('Unable to delete user space', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly: true): asserts user is User | AdminUser | GuestUser
  checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly?: false): UserModel
  checkUser(user: User | AdminUser | GuestUser | null | undefined, checkOnly = false): UserModel | void {
    if (!user) {
      throw new HttpException('User not found', HttpStatus.NOT_FOUND)
    }
    if (!checkOnly) {
      return new UserModel(user, true)
    }
  }

  private async renameUserSpace(oldLogin: string, newLogin: string): Promise<boolean> {
    const currentUserSpace: string = UserModel.getHomePath(oldLogin)
    if (!(await isPathExists(currentUserSpace))) {
      this.logger.warn({ tag: this.renameUserSpace.name, msg: `user space *${oldLogin}* does not exist : ${currentUserSpace}` })
      return false
    }
    const newUserSpace: string = UserModel.getHomePath(newLogin)
    if (await isPathExists(newUserSpace)) {
      this.logger.warn({ tag: this.renameUserSpace.name, msg: `user space *${newLogin}* already exists : ${newUserSpace}` })
      return false
    }
    try {
      await moveFiles(currentUserSpace, newUserSpace)
      return true
    } catch (e) {
      // try to restore
      await moveFiles(newUserSpace, currentUserSpace, true)
      this.logger.error({
        tag: this.renameUserSpace.name,
        msg: `unable to rename user space from *${currentUserSpace}* to *${newUserSpace}* : ${toErrorMessage(e)}`
      })
      return false
    }
  }

  private async checkGroupNameExists(groupName: string): Promise<void> {
    if (await this.adminQueries.usersQueries.checkGroupNameExists(groupName)) {
      throw new HttpException('Name already used', HttpStatus.BAD_REQUEST)
    }
  }

  private validateUserLogin(login: string): void {
    if (!isValidUserLogin(login)) {
      throw new HttpException('Invalid login', HttpStatus.BAD_REQUEST)
    }
  }

  private async loginOrEmailAlreadyUsed(login: string, email: string) {
    const exists = await this.adminQueries.usersQueries.checkUserExists(login, email)
    if (exists) {
      throw new HttpException(`${exists.login === login ? 'Login' : 'Email'} already used`, HttpStatus.BAD_REQUEST)
    }
  }
}