class-validator#validateOrReject TypeScript Examples

The following examples show how to use class-validator#validateOrReject. 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: role-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
listHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Role List Handler Event: %o', event);

    const roleListDto = Object.assign(new RoleListDto(), event.queryStringParameters) as RoleListDto;
    await validateOrReject(plainToClass(RoleListDto, roleListDto));

    const repository = _applicationContainer.get<ProjectionRepository<RoleProjection>>(DynamoProjectionRepository);
    const roleProjections = await repository.list(process.env.projectionRolesTable, roleListDto);

    return { statusCode: HttpStatus.OK, body: JSON.stringify(roleProjections) };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #2
Source File: signUp.ts    From tezos-academy with MIT License 6 votes vote down vote up
signUp = async (ctx: Context, next: Next): Promise<void> => {
  const signUpArgs = plainToClass(SignUpInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(signUpArgs, { forbidUnknownValues: true }).catch(firstError)
  let { username, email, password, recaptchaToken } = signUpArgs

  username = username.toLowerCase()
  email = email.toLowerCase()

  await verifyRecaptchaToken(recaptchaToken)

  const emailAlreadyTaken: User | null = await UserModel.findOne({ email }).lean()
  if (emailAlreadyTaken) throw new ResponseError(400, 'Email is already taken')

  const usernameAlreadyTaken: User | null = await UserModel.findOne({ username }).lean()
  if (usernameAlreadyTaken) throw new ResponseError(400, 'Username is already taken')

  const hashedPassword = await hash(password, 12)
  const user: User = await UserModel.create({ email, username, hashedPassword } as User)
  const publicUser: PublicUser = toPublicUser(user)

  const jwt: Jwt = getSignedJwt(user._id.toHexString(), user.username)

  const response: SignUpOutputs = { jwt, user: publicUser }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #3
Source File: resetPassword.ts    From tezos-academy with MIT License 6 votes vote down vote up
resetPassword = async (ctx: Context, next: Next): Promise<void> => {
  const resetPasswordArgs = plainToClass(ResetPasswordInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(resetPasswordArgs, { forbidUnknownValues: true }).catch(firstError)
  const { solution, token, newPassword } = resetPasswordArgs

  const captcha: Captcha = (await CaptchaModel.findOne({
    token,
    captchaFor: CaptchaFor.CAPTCHA_FOR_RESET_PASSWORD,
  }).lean()) as Captcha
  if (!captcha) throw new ResponseError(401, 'Wrong token key')

  const user: User = (await UserModel.findOne({ _id: captcha.userId }).lean()) as User
  if (!user) throw new ResponseError(404, 'User not found')

  await rateLimit(user._id)

  await verifyCaptcha(user._id, solution, CaptchaFor.CAPTCHA_FOR_RESET_PASSWORD)

  const hashedPassword: string = await hash(newPassword, 12)

  await UserModel.updateOne({ _id: user._id }, { hashedPassword }).exec()

  await CaptchaModel.deleteOne({ _id: captcha._id }).exec()

  ctx.status = 200
  ctx.body = {}

  await next()
}
Example #4
Source File: login.ts    From tezos-academy with MIT License 6 votes vote down vote up
login = async (ctx: Context, next: Next): Promise<void> => {
  const loginArgs = plainToClass(LoginInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(loginArgs, { forbidUnknownValues: true }).catch(firstError)
  let { usernameOrEmail, password, recaptchaToken } = loginArgs

  usernameOrEmail = usernameOrEmail.toLowerCase()

  await verifyRecaptchaToken(recaptchaToken)

  let user: User | null = await UserModel.findOne({ email: usernameOrEmail }).lean()
  if (!user) {
    user = await UserModel.findOne({ username: usernameOrEmail }).lean()
  }
  if (!user) throw new ResponseError(401, 'Wrong username or password')

  const publicUser: PublicUser = toPublicUser(user)

  await rateLimit(user._id, QuotaType.LOGIN)

  await matchPassword(password, user.hashedPassword)

  const jwt: Jwt = getSignedJwt(user._id.toHexString(), user.username)

  const response: LoginOutputs = { jwt, user: publicUser }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #5
Source File: forgotPassword.ts    From tezos-academy with MIT License 6 votes vote down vote up
forgotPassword = async (ctx: Context, next: Next): Promise<void> => {
  const forgotPasswordArgs = plainToClass(ForgotPasswordInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(forgotPasswordArgs, { forbidUnknownValues: true }).catch(firstError)
  const { usernameOrEmail, recaptchaToken } = forgotPasswordArgs

  await verifyRecaptchaToken(recaptchaToken)

  let user: User | null = await UserModel.findOne({ email: usernameOrEmail }).lean()
  if (!user) {
    user = await UserModel.findOne({ username: usernameOrEmail }).lean()
  }
  if (!user) throw new ResponseError(401, 'Wrong username or password')

  await rateLimit(user._id, QuotaType.NEW_CAPTCHA)

  const captcha: Captcha = await createCaptcha(user._id, CaptchaFor.CAPTCHA_FOR_RESET_PASSWORD)

  await sendEmailForgotPassword(user.email, captcha.solution, captcha.token)

  const response: ForgotPasswordOutputs = { token: captcha.token }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #6
Source File: changePassword.ts    From tezos-academy with MIT License 6 votes vote down vote up
changePassword = async (ctx: Context, next: Next): Promise<void> => {
  const changePasswordArgs = plainToClass(ChangePasswordInputs, ctx.request.body, {
    excludeExtraneousValues: true,
  })
  await validateOrReject(changePasswordArgs, { forbidUnknownValues: true }).catch(firstError)
  const { password, newPassword } = changePasswordArgs

  const user: User = await authenticate(ctx)

  await rateLimit(user._id)

  await matchPassword(password, user.hashedPassword)

  const hashedPassword = await hash(newPassword, 12)
  await UserModel.updateOne({ _id: user._id }, { hashedPassword }).exec()

  ctx.status = 200
  ctx.body = {}

  await next()
}
Example #7
Source File: addProgress.ts    From tezos-academy with MIT License 6 votes vote down vote up
addProgress = async (ctx: Context, next: Next): Promise<void> => {
  const addProgressArgs = plainToClass(AddProgressInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(addProgressArgs, { forbidUnknownValues: true }).catch(firstError)
  const { chapterDone } = addProgressArgs

  const user: User = await authenticate(ctx)

  await rateLimit(user._id)

  await UserModel.updateOne(
    { _id: user._id },
    { $addToSet: { progress: chapterDone } },
  ).exec()

  const updatedUser: User = await UserModel.findOne(
    { _id: user._id },
  ).lean()  as User

  const publicUser: PublicUser = toPublicUser(updatedUser)
  
  const response: AddProgressOutputs = { user: publicUser }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #8
Source File: getPublicUser.ts    From tezos-academy with MIT License 6 votes vote down vote up
getPublicUser = async (ctx: Context, next: Next): Promise<void> => {
  const getPublicUserArgs = plainToClass(GetPublicUserInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(getPublicUserArgs, { forbidUnknownValues: true }).catch(firstError)
  const { username } = getPublicUserArgs

  const user: PublicUser = (await UserModel.findOne({ username }, PUBLIC_USER_MONGO_SELECTOR).lean()) as PublicUser
  if (!user) throw new ResponseError(404, 'User not found')

  const response: GetPublicUserOutputs = { user }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #9
Source File: auth.service.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
   * Create a user document in firestore for first time user.
   * @param userDecodedToken: any
   */
  private async createFirstTimeLoginUser(
    userDecodedToken: any,
    loginNormalUserRequestDto: LoginNormalUserRequestDto
  ): Promise<void> {
    const createUserDto: CreateUserDto = new CreateUserDto()
    createUserDto.userId = userDecodedToken.uid
    // Validate the create User data object which will be saved to firestore.
    try {
      await validateOrReject(createUserDto)
    } catch (errors) {
      throw new BadRequestException(errors, 'Request validation failed')
    }

    const createUserProfileDto: CreateUserProfileDto = new CreateUserProfileDto()
    createUserProfileDto.prefecture = loginNormalUserRequestDto.prefecture

    await this.usersService.createOneUser(createUserDto, createUserProfileDto)
  }
Example #10
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
removeRoleHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Remove Role Handler Event: %o', event);

    const userRemoveRoleDto = Object.assign(new UserRemoveRoleDto(), event.pathParameters) as UserRemoveRoleDto;

    await validateOrReject(userRemoveRoleDto);
    await _applicationContainer.get<RemoveUserRoleHandler>(RemoveUserRoleHandler).handle(new RemoveUserRole(userRemoveRoleDto.id, userRemoveRoleDto.roleId));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #11
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
addRoleHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Add Role Handler Event: %o', event);

    const userAddRoleDto = Object.assign(new UserAddRoleDto(), JSON.parse(event.body), event.pathParameters) as UserAddRoleDto;

    await validateOrReject(userAddRoleDto);
    await _applicationContainer.get<AddUserRoleHandler>(AddUserRoleHandler).handle(new AddUserRole(userAddRoleDto.id, userAddRoleDto.roleId));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #12
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
disableHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User Disable Handler Event: %o', event);

    const userDisableDto = Object.assign(new UserDisableDto(), event.pathParameters) as UserDisableDto;

    await validateOrReject(userDisableDto);
    await _applicationContainer.get<DisableUserHandler>(DisableUserHandler).handle(new DisableUser(userDisableDto.id));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #13
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
putHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User Put Handler Event: %o', event);

    const userPutDto = Object.assign(new UserPutDto(), JSON.parse(event.body), event.pathParameters) as UserPutDto;

    await validateOrReject(userPutDto);
    await _applicationContainer.get<UpdateUserHandler>(UpdateUserHandler).handle(new UpdateUser(userPutDto.id, userPutDto.firstName, userPutDto.lastName));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #14
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
postHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User Post Handler Event: %o', event);

    const userPostDto = Object.assign(new UserPostDto(), JSON.parse(event.body)) as UserPostDto;
    await validateOrReject(userPostDto);
    await _applicationContainer.get<RegisterUserHandler>(RegisterUserHandler).handle(new RegisterUser(userPostDto.id, userPostDto.email));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #15
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
getHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User Get Handler Event: %o', event);

    const userGetDto = Object.assign(new UserGetDto(), event.pathParameters) as UserGetDto;
    await validateOrReject(userGetDto);

    const repository = _applicationContainer.get<ProjectionRepository<UserProjection>>(DynamoProjectionRepository);
    const userProjection = await repository.get(process.env.projectionUsersTable, userGetDto.id);

    return {
      statusCode: userProjection ? HttpStatus.OK : HttpStatus.NOT_FOUND,
      body: userProjection ? JSON.stringify(userProjection) : null
    };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #16
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
listHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User List Handler Event: %o', event);

    const userListDto = Object.assign(new UserListDto(), event.queryStringParameters) as UserListDto;
    await validateOrReject(plainToClass(UserListDto, userListDto));

    const repository = _applicationContainer.get<ProjectionRepository<UserProjection>>(DynamoProjectionRepository);
    const userProjections = await repository.list(process.env.projectionUsersTable, userListDto);

    return { statusCode: HttpStatus.OK, body: JSON.stringify(userProjections) };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #17
Source File: role-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
disableHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Role Disable Handler Event: %o', event);

    const roleDisableDto = Object.assign(new RoleDisableDto(), event.pathParameters) as RoleDisableDto;

    await validateOrReject(roleDisableDto);
    await _applicationContainer.get<DisableUserRoleHandler>(DisableUserRoleHandler).handle(new DisableRole(roleDisableDto.id));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #18
Source File: role-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
postHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Role Post Handler Event: %o', event);

    const rolePostDto = Object.assign(new RolePostDto(), JSON.parse(event.body)) as RolePostDto;
    await validateOrReject(rolePostDto);
    await _applicationContainer.get<CreateRoleHandler>(CreateRoleHandler).handle(new CreateRole(rolePostDto.id, rolePostDto.name));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #19
Source File: role-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
getHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Role Get Handler Event: %o', event);

    const roleGetDto = Object.assign(new RoleGetDto(), event.pathParameters) as RoleGetDto;
    await validateOrReject(roleGetDto);

    const repository = _applicationContainer.get<ProjectionRepository<RoleProjection>>(DynamoProjectionRepository);
    const roleProjection = await repository.get(process.env.projectionRolesTable, roleGetDto.id);

    return {
      statusCode: roleProjection ? HttpStatus.OK : HttpStatus.NOT_FOUND,
      body: roleProjection ? JSON.stringify(roleProjection) : null
    };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #20
Source File: helpers.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
validateBody = async <T>(
  obj: ClassType<T>,
  body: string | null,
  validateOptions?: ValidationOptions
): Promise<T> => {
  const raw: any = plainToClass(obj, JSON.parse(body ?? '{}'));
  await validateOrReject(raw, {
    ...validateOptions,
    whitelist: true,
    forbidUnknownValues: true
  });
  return raw;
}
Example #21
Source File: order.entity.ts    From rest-api.ts with MIT License 5 votes vote down vote up
@BeforeInsert()
  @BeforeUpdate()
  async validate() {
    await validateOrReject(this);
  }
Example #22
Source File: placement.entity.ts    From rest-api.ts with MIT License 5 votes vote down vote up
@BeforeInsert()
  @BeforeUpdate()
  async validate() {
    await validateOrReject(this);
  }
Example #23
Source File: product.entity.ts    From rest-api.ts with MIT License 5 votes vote down vote up
@BeforeInsert()
  @BeforeUpdate()
  async validate() {
    await validateOrReject(this);
  }
Example #24
Source File: user.entity.ts    From rest-api.ts with MIT License 5 votes vote down vote up
@BeforeInsert()
  @BeforeUpdate()
  async validate() {
    await validateOrReject(this);
  }