@nestjs/common#ConflictException TypeScript Examples

The following examples show how to use @nestjs/common#ConflictException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.MENTOR)
  @ApiResponse({ type: TrackDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN })
  @ApiBearerAuth()
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  async create(@Body() input: CreateTrackDto): Promise<TrackDto> {
    const exist = await this.trackService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (exist)
      throw new ConflictException(
        `Track with the title "${exist.title}" already exists`
      );
    return await super.create(input);
  }
Example #2
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('register')
  @ApiConflictResponse({ type: ApiException })
  @ApiResponse({ type: RegisterUserResDto, status: HttpStatus.CREATED })
  async register(@Body() input: RegisterUserDto): Promise<RegisterUserResDto> {
    const exist = await this.usersService.findOneAsync({ email: input.email });
    if (exist)
      throw new ConflictException('User with the email already exists');
    const user = this.usersService.createEntity(input);
    const saved = await this.usersService.insertAsync(user);

    return { canLogin: saved.isEmailVerified };
  }
Example #3
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('send-email-confirmation-token')
  @HttpCode(HttpStatus.OK)
  async sendEmailVerifyToken(@Body() input: AcctVerifyDto): Promise<void> {
    const { clientBaseUrl, tokenParamName, emailParamName, email } = input;
    const user = await this.usersService.findOneAsync({ email });
    if (!user) throw new NotFoundException('User with email does not exist');
    if (user.isEmailVerified)
      throw new ConflictException('Email has already been confirmed');
    const token = await this.authService.generateTempToken({
      user,
      type: TokenType.EMAIL,
      expiresInMins: 60 * 24
    });
    if (!token) return;
    const url = new URL(clientBaseUrl);
    url.searchParams.set(tokenParamName, token);
    url.searchParams.set(emailParamName, email);
    let html = await fs.promises.readFile('./src/templates/welcome.html', {
      encoding: 'utf8'
    });
    html = html
      .replace('%fullName%', user.fullName)
      .replace('%verificationUrl%', url.href);

    this.mailService.sendMailAsync({
      from: configuration().appEmail,
      to: user.email,
      html,
      date: new Date(Date.now()),
      subject: 'Welcome to Code Clan Nigeria'
    });
  }
Example #4
Source File: application.service.ts    From uniauth-backend with MIT License 6 votes vote down vote up
async create(createApplicationDto: CreateApplicationDto, authorizedUser: LoggedInUser): Promise<Application> {
    try {
      const clientSecret = generateUUID();
      const creationDate = new Date();

      const newApplication = new this.applicationModel({
        ...createApplicationDto,
        clientSecret,
        creationDate,
        admin: authorizedUser.id,
      });

      await newApplication.save();
      return newApplication;
    } catch (e) {
      this.logger.error(e);
      throw new ConflictException(e.message);
    }
  }
Example #5
Source File: categories.controller.spec.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
describe('Categories Controller', () => {
  let controller: CategoriesController;
  const categoryService: any = {
    findOneAsync: () => "exist"
  }
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [CategoriesModule, DbTest]
    }).overrideProvider(BaseService)
      .useValue(categoryService).
      overrideProvider(CategoriesService)
      .useValue(categoryService)
      .compile();

    controller = module.get<CategoriesController>(CategoriesController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });
  let input: CreateCategoryDto;
  it('should throw conflict error', async () => {
    input = { description: 'description', name: 'name' }
    await expect(controller.create(input)).rejects.toThrowError(ConflictException)
  });
  it('should create new category', async () => {
    categoryService.findOneAsync = () => null;
    categoryService.createEntity = () => input
    categoryService.insertAsync = () => Promise.resolve();
    const result = await controller.create(input);
    expect(result).toMatchObject(input)
  });
});
Example #6
Source File: categories.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: CategoryDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateCategoryDto): Promise<CategoryDto> {
    const exist = await this.categoryService.findOneAsync({
      title: input.name.toUpperCase()
    });

    if (exist)
      throw new ConflictException(
        `Category with the name "${exist.name}" already exists`
      );

    return super.create(input);
  }
Example #7
Source File: courses.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: CourseDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateCourseDto): Promise<CourseDto> {
    const exist = await this.courseService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (exist)
      throw new ConflictException(
        `Course with the title "${exist.title}" already exists`
      );
    return super.create(input);
  }
Example #8
Source File: mentor.service.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
async reassignMentee(input: {
    trackId: string;
    menteeId: string;
    fromMentorId: string;
    toMentorId: string;
    adminId: any;
  }): Promise<void> {
    let mentorMentee = await this.mentorMenteeModel.findOne({
      mentor: input.fromMentorId,
      mentee: input.menteeId
    });
    if (mentorMentee) mentorMentee.delete();
    mentorMentee = await this.mentorMenteeModel.findOne({
      mentor: input.toMentorId,
      mentee: input.menteeId
    });
    if (mentorMentee)
      throw new ConflictException('Mentee already has a Mentor');
    await this.mentorMenteeModel.create({
      mentor: input.toMentorId,
      mentee: input.menteeId,
      track: input.trackId
    });
  }
Example #9
Source File: stages.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: StageDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateStageDto): Promise<StageDto> {
    const track = await this.trackService.findByIdAsync(input.track);
    if (!track) {
      throw new NotFoundException(
        `Track with id ${input.track} does not exist`
      );
    }

    const stage = await this.stageService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (stage) {
      throw new ConflictException(
        `Stage with the title "${stage.title}" already exists`
      );
    }
    return await super.create(input);
  }
Example #10
Source File: tasks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.MENTOR)
  @ApiResponse({ type: TaskDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  async create(@Body() input: CreateTaskDto): Promise<TaskDto> {
    const task = await this.tasksService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (task) {
      throw new ConflictException(
        `Task with the title "${task.title}" already exists`
      );
    }
    const stage = await this.stageService.findByIdAsync(input.stage);
    if (!stage)
      throw new NotFoundException(`Stage with ${input.stage} not found`);
    const track = await this.trackService.findByIdAsync(input.track);
    if (!track)
      throw new NotFoundException(`Track with ${input.track} not found`);
    const course = await this.coursesService.findByIdAsync(input.course);

    if (!course)
      throw new NotFoundException(`Course with ${input.course} not found`);

    return await super.create(input);
  }
Example #11
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('confirm-email')
  @HttpCode(HttpStatus.OK)
  async verifyEmailToken(@Body() input: ValidateTokenInput): Promise<void> {
    const { email, token } = input;
    const user = await this.usersService.findOneAsync({ email });
    if (!user) throw new NotFoundException('User does not exist');
    if (user.isEmailVerified)
      throw new ConflictException('Email already verified');
    await this.authService.validateEmailToken({
      userId: user.id,
      plainToken: token
    });
  }
Example #12
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('create_with_thumbnail')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.MENTOR)
  @ApiResponse({ type: TrackDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @UseInterceptors(FileInterceptor('thumbnail'))
  @ApiConsumes('multipart/form-data')
  @ApiBearerAuth()
  async createTrack(
    @Body() input: CreateWithThumbnailTrackDto,
    @UploadedFile() thumbnail: BufferedFile,
    @Req() req: Request
  ): Promise<TrackDto> {
    if (!thumbnail)
      throw new BadRequestException('Thumbnail image cannot be empty');
    if (thumbnail.mimetype.split('/')[0] !== 'image')
      throw new UnsupportedMediaTypeException('File is not an image');
    if (thumbnail.size / ONE_KB > 200)
      throw new BadRequestException('File cannot be larger than 200KB');
    const exist = await this.trackService.findOneAsync({
      title: input.title.toUpperCase()
    });
    if (exist)
      throw new ConflictException(
        `Track with the title "${exist.title}" already exists`
      );

    const userId = req.user['userId'];
    const thumbnailUrl = await uploadFileToCloud(thumbnail, 'avatars', userId);
    const dto = input as any;
    dto.thumbnailUrl = thumbnailUrl;
    delete dto.thumbnail;
    return await super.create(dto);
  }
Example #13
Source File: users.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: UserDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateUserDto): Promise<UserDto> {
    const exist = await this.usersService.findOneAsync({
      title: input.email.toLowerCase()
    });
    if (exist) {
      throw new ConflictException(
        `User with the email "${exist.email}" already exists`
      );
    }
    return super.create(input);
  }
Example #14
Source File: course.service.ts    From edu-server with MIT License 6 votes vote down vote up
// Create a Review
  async addReview(
    courseId: Schema.Types.ObjectId,
    createReviewDto: CreateReviewDto,
  ): Promise<any> {
    try {
      const course = await this.CourseModel.findById(courseId).populate(
        'reviews',
      );
      if (course) {
        const reviewExist = course.reviews.some(
          (review) =>
            review.reviewerId.toString() === createReviewDto.reviewerId,
        );
        if (reviewExist) {
          throw new ConflictException('You have already reviewed the course!');
        } else {
          const newReview = new this.ReviewModel(createReviewDto);
          await newReview.save();
          course.reviews.push(newReview);
          await course.save();
          return newReview;
        }
      } else {
        throw new NotFoundException(
          'The course id is invalid or the course no longer exists',
        );
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #15
Source File: mentor.service.ts    From edu-server with MIT License 6 votes vote down vote up
// assign course to mentor
  async assignCourseToMentor(
    mentorId: Schema.Types.ObjectId,
    courseId: Schema.Types.ObjectId,
  ): Promise<any> {
    try {
      const mentor = await this.mentorModel.findById(mentorId);
      if (mentor) {
        const doesCourseExists = await this.courseModel.exists({
          _id: courseId['courseId'],
        });
        if (doesCourseExists) {
          const isAlreadypresent = mentor.courses.includes(
            courseId['courseId'],
          );
          if (!isAlreadypresent) {
            mentor.courses.push(courseId['courseId']);
            await mentor.save();
            return mentor;
          } else {
            throw new ConflictException('Course Already Assigned');
          }
        } else {
          throw new NotFoundException('Course not found');
        }
      } else {
        throw new NotFoundException('Mentor not found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #16
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// post a single User
  async addUser(request, CreateUserDTO: CreateUserDTO): Promise<User> {
    try {
      const { email, fId, role } = request['user'];
      const userExists = await this.userModel.findOne({ email: email }).lean();
      if (userExists) {
        throw new ConflictException(`User with email ${email} already exists`);
      }
      const userToBeCreated = { ...CreateUserDTO, email, fId, role };
      const newUser = await new this.userModel(userToBeCreated);
      return newUser.save();
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #17
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// adds wishlisted course
  async addWishlist(cId: Schema.Types.ObjectId) {
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });

      if (user) {
        const doesWishlistExists = await this.courseModel.exists({
          _id: cId['cId'],
        });
        if (doesWishlistExists) {
          const doesUserExistInWishList = user.wishlist.includes(cId['cId']);
          if (!doesUserExistInWishList) {
            user.wishlist.push(cId['cId']);
            await user.save();
            return user;
          } else {
            throw new ConflictException('Course Already Exists In WishList');
          }
        } else {
          throw new NotFoundException("Wishlisted Course doesn't exist");
        }
      } else {
        throw new NotFoundException('User Not Found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #18
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// adds a course to Cart
  async addCartList(cId: Schema.Types.ObjectId) {
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });

      if (user) {
        const doesCartListExists = await this.courseModel.exists({
          _id: cId['cId'],
        });
        if (doesCartListExists) {
          const doesUserExistInCartList = user.cartList.includes(cId['cId']);
          if (!doesUserExistInCartList) {
            user.cartList.push(cId['cId']);
            await user.save();
            return user;
          } else {
            throw new ConflictException('Course Already Exists In Cart');
          }
        } else {
          throw new NotFoundException("Course doesn't exist");
        }
      } else {
        throw new NotFoundException('User Not Found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #19
Source File: register.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Post()
    register(
        @Body() registerDto: RegisterDto,
        @Res() res: Response): Observable<Response> {
        const username = registerDto.username;

        return this.userService.existsByUsername(username).pipe(
            mergeMap(exists => {
                if (exists) {
                    throw new ConflictException(`username:${username} is existed`)
                }
                else {
                    const email = registerDto.email;
                    return this.userService.existsByEmail(email).pipe(
                        mergeMap(exists => {
                            if (exists) {
                                throw new ConflictException(`email:${email} is existed`)
                            }
                            else {
                                return this.userService.register(registerDto).pipe(
                                    map(user =>
                                        res.location('/users/' + user.id)
                                            .status(201)
                                            .send()
                                    )
                                );
                            }
                        })
                    );
                }
            })
        );
    }
Example #20
Source File: user.repository.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
async register(authCredentialsDto: AuthCredentialsDto): Promise<void> {
    const { phone, pwd } = authCredentialsDto;

    // const exists = this.findOne({ username })

    // if (exists) {
    //   // throw some error
    // }
    // const salt = await bcrypt.genSalt()
    // console.log('TCL: UserRepository -> salt', salt)

    // const user = new User()
    const user = this.create();
    user.phone = phone;
    user.salt = await bcrypt.genSalt();
    user.pwd = await this.hashPassword(pwd, user.salt);
    user.userId = uuid();

    try {
      await user.save();
    } catch (error) {
      if (error.code === '23505') {
        // duplicate username
        throw new ConflictException('Username already exists');
      } else {
        throw new InternalServerErrorException();
      }
    }
  }
Example #21
Source File: application.service.ts    From uniauth-backend with MIT License 6 votes vote down vote up
async delete(id: string) {
    try {
      const AppUser = await this.applicationModel.findOne({ _id: id }).populate('participants', '_id');
      AppUser.participants.forEach(async (user) => {
        const User = await this.userModel.findById(user);
        User.authorizedApplications = User.authorizedApplications.filter((_id) => _id.toString() !== id);
        await User.save();
      });
      await this.applicationModel.findByIdAndDelete({ _id: id });
    } catch (e) {
      this.logger.error(e);
      throw new ConflictException(e.message);
    }
  }
Example #22
Source File: auth.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async signup(payload: SignupInput): Promise<string> {
    const hashedPassword = await this.passwordService.hashPassword(
      payload.password
    );

    try {
      const account = await this.accountService.createAccount({
        data: {
          email: payload.email,
          firstName: payload.firstName,
          lastName: payload.lastName,
          password: hashedPassword
          //role: 'USER'
        }
      });

      const workspace = await this.createWorkspace(
        payload.workspaceName,
        account
      );

      const [user] = workspace.users;

      await this.accountService.setCurrentUser(account.id, user.id);

      return this.prepareToken(user);
    } catch (error) {
      throw new ConflictException(error);
    }
  }
Example #23
Source File: user.service.ts    From uniauth-backend with MIT License 6 votes vote down vote up
async create(createUserDto: CreateUserDto): Promise<User> {
    try {
      const { registrationNumber, name } = createUserDto;
      let { password, collegeEmail } = createUserDto;

      const regNumber = new RegistrationNumberWorker(registrationNumber);
      const branch = regNumber.getBranch();
      const batch = regNumber.getYear();
      password = await bcrypt.hashSync(password, 10);
      collegeEmail = collegeEmail.toLowerCase();

      const user = new this.userModel({ name, collegeEmail, branch, batch, password, registrationNumber });
      await user.save();
      return user;
    } catch (e) {
      throw new ConflictException(e.message);
    }
  }
Example #24
Source File: user.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async delete(userId: string): Promise<User> {
    const user = this.findUser({
      where: {
        id: userId
      }
    });

    if (!user) {
      throw new ConflictException(`Can't find user with ID ${userId}`);
    }

    return this.prisma.user.update({
      where: {
        id: userId
      },
      data: {
        deletedAt: new Date()
      }
    });
  }
Example #25
Source File: workspace.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async revokeInvitation(args: RevokeInvitationArgs): Promise<Invitation> {
    const invitation = await this.prisma.invitation.findFirst({
      ...args,
      where: {
        ...args.where,
        newUser: null
      }
    });

    if (!invitation) {
      throw new ConflictException(`Invitation cannot be found`);
    }

    return this.prisma.invitation.delete({
      where: {
        id: invitation.id
      }
    });
  }
Example #26
Source File: workspace.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async resendInvitation(args: ResendInvitationArgs): Promise<Invitation> {
    const invitation = await this.prisma.invitation.findFirst({
      ...args,
      where: {
        ...args.where,
        newUser: null
      },
      include: {
        invitedByUser: {
          include: {
            account: true
          }
        }
      }
    });

    if (!invitation) {
      throw new ConflictException(`Invitation cannot be found`);
    }

    const updatedInvitation = await this.prisma.invitation.update({
      where: {
        id: invitation.id
      },
      data: {
        tokenExpiration: addDays(new Date(), INVITATION_EXPIRATION_DAYS)
      }
    });

    await this.mailService.sendInvitation({
      to: invitation.email,
      invitationToken: invitation.token,
      invitedByUserFullName: invitation.invitedByUser.account.email
    });

    return updatedInvitation;
  }
Example #27
Source File: workspace.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async deleteUser(currentUser: User, args: DeleteUserArgs): Promise<User> {
    const user = await this.userService.findUser({
      ...args,
      include: {
        workspace: true
      }
    });

    if (!user) {
      throw new ConflictException(`Can't find user ${args.where.id}`);
    }
    if (user.isOwner) {
      throw new ConflictException(`Can't delete the workspace owner`);
    }

    if (currentUser.workspace.id !== user.workspace.id) {
      throw new ConflictException(
        `The requested user is not in the current user's workspace`
      );
    }

    return this.userService.delete(args.where.id);
  }
Example #28
Source File: admins.service.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
async createOneAdminUser(
    requestAdminUser: RequestAdminUser,
    createAdminRequest: CreateAdminRequestDto
  ): Promise<void> {
    // Check if an admin already exists with this email.
    const adminExists = await this.adminsRepository.findOneByEmail(createAdminRequest.email)
    if (adminExists) {
      throw new ConflictException('An admin with this email already exists')
    }

    // Start preparing the create admin object. It will be passed to the repo function.
    const createAdminDto: CreateAdminDto = new CreateAdminDto()
    createAdminDto.email = createAdminRequest.email
    createAdminDto.addedByAdminUserId = requestAdminUser.uid
    createAdminDto.addedByAdminEmail = requestAdminUser.email
    createAdminDto.userAdminRole = createAdminRequest.adminRole
    createAdminDto.accessControlList = [getSuperAdminACLKey()]
    // Check if the user has access to create new user with desired adminRole in the payload.
    // Also, determine what accessKey will be added to the new created admin.
    switch (createAdminRequest.adminRole) {
      case AdminRole.superAdminRole:
        if (!canUserCreateSuperAdmin(requestAdminUser.userAccessKey)) {
          throw new UnauthorizedException('Insufficient access to create this adminRole')
        }
        createAdminDto.userAccessKey = getSuperAdminACLKey()
        // No need to add any ACL Key in accessControlList, since it already contains the
        // superAdmin key added above.
        break

      case AdminRole.nationalAdminRole:
        if (!canUserCreateNationalAdmin(requestAdminUser.userAccessKey)) {
          throw new UnauthorizedException('Insufficient access to create this adminRole')
        }
        throw new UnauthorizedException('WIP. nationalAdminRole not supported yet')

      case AdminRole.prefectureAdminRole:
        if (
          !canUserCreatePrefectureAdmin(
            requestAdminUser.userAccessKey,
            createAdminRequest.prefectureId
          )
        ) {
          throw new UnauthorizedException('Insufficient access to create this adminRole')
        }
        // Check if prefectureId is valid
        const isPrefectureCodeValid = await this.prefecturesService.isPrefectureCodeValid(
          createAdminRequest.prefectureId
        )
        if (!isPrefectureCodeValid) {
          throw new BadRequestException('Invalid prefectureId value')
        }

        createAdminDto.userAccessKey = getPrefectureAdminACLKey(createAdminRequest.prefectureId)
        createAdminDto.prefectureId = createAdminRequest.prefectureId
        createAdminDto.accessControlList.push(
          getNationalAdminACLKey(),
          getPrefectureAdminACLKey(createAdminRequest.prefectureId)
        )

        break

      default:
        throw new BadRequestException('Invalid adminRole value')
    }

    let firebaseUserRecord: firebaseAdmin.auth.UserRecord
    try {
      firebaseUserRecord = await firebaseAdmin.auth().createUser({
        email: createAdminRequest.email,
        emailVerified: false,
        disabled: false,
      })
    } catch (error) {
      throw new BadRequestException(error.message)
    }

    createAdminDto.adminUserId = firebaseUserRecord.uid

    return this.adminsRepository.createOne(createAdminDto)
  }
Example #29
Source File: workspace.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
async inviteUser(
    currentUser: User,
    args: InviteUserArgs
  ): Promise<Invitation | null> {
    const { workspace, id: currentUserId, account } = currentUser;

    if (isEmpty(args.data.email)) {
      throw new ConflictException(`email address is required to invite a user`);
    }

    const existingUsers = await this.userService.findUsers({
      where: {
        account: { email: args.data.email },
        workspace: { id: workspace.id }
      }
    });

    if (existingUsers.length) {
      throw new ConflictException(
        `User with email ${args.data.email} already exist in the workspace.`
      );
    }

    const existingInvitation = await this.prisma.invitation.findUnique({
      where: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        workspaceId_email: {
          email: args.data.email,
          workspaceId: workspace.id
        }
      }
    });

    if (existingInvitation) {
      throw new ConflictException(
        `Invitation with email ${args.data.email} already exist in the workspace.`
      );
    }

    const currentUserAccount = await this.prisma.account.findUnique({
      where: {
        id: account.id
      }
    });

    const invitation = await this.prisma.invitation.create({
      data: {
        email: args.data.email,
        workspace: {
          connect: {
            id: workspace.id
          }
        },
        invitedByUser: {
          connect: {
            id: currentUserId
          }
        },
        token: cuid(),
        tokenExpiration: addDays(new Date(), INVITATION_EXPIRATION_DAYS)
      }
    });

    await this.mailService.sendInvitation({
      to: invitation.email,
      invitationToken: invitation.token,
      invitedByUserFullName: currentUserAccount.email
    });

    return invitation;
  }