How to use the @loopback/rest.HttpErrors.BadRequest function in @loopback/rest

To help you get started, we’ve selected a few @loopback/rest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
async createOrder(
    @param.path.string('userId') userId: string,
    @requestBody() order: Order,
  ): Promise {
    // validate the payload value
    // has nothing to do with authorization
    if (userId !== order.userId) {
      throw new HttpErrors.BadRequest(
        `User id does not match: ${userId} !== ${order.userId}`,
      );
    }
    delete order.userId;
    return this.userRepo.orders(userId).create(order);
  }
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
async login(
    @requestBody()
    req: LoginRequest,
  ): Promise<{
    code: string;
  }> {
    if (!this.client || !this.user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    } else if (!req.client_secret) {
      throw new HttpErrors.BadRequest(AuthErrorKeys.ClientSecretMissing);
    }
    try {
      const codePayload: ClientAuthCode = {
        clientId: req.client_id,
        userId: this.user.id,
      };
      const token = jwt.sign(codePayload, this.client.secret, {
        expiresIn: this.client.authCodeExpiration,
        audience: req.client_id,
        subject: req.username,
        issuer: process.env.JWT_ISSUER,
      });
      return {
        code: token,
      };
    } catch (error) {
github gobackhuoxing / first-web-game-lb4 / firstgame / src / controllers / admin.controller.ts View on Github external
@param.query.string('admin_code') admin_code: string,
    @requestBody() character: Character,
  ): Promise {
      if(admin_code != '901029'){
        throw new HttpErrors.Forbidden('WRONG_ADMIN_CODE');
      }

      character.permissions = [PermissionKey.ViewOwnUser,
                               PermissionKey.CreateUser,
                               PermissionKey.UpdateOwnUser,
                               PermissionKey.DeleteOwnUser,
                               PermissionKey.UpdateAnyUser,
                               PermissionKey.ViewAnyUser,
                               PermissionKey.DeleteAnyUser];
      if (await this.characterRepository.exists(character.email)){
        throw new HttpErrors.BadRequest(`This email already exists`);
      }
      else {
        const savedCharacter = await this.characterRepository.create(character);
        delete savedCharacter.password;
        return savedCharacter;
      }
  }
github iqbaldjulfri / lb4-jwt-role-based-auth-sample / src / controllers / user.controller.ts View on Github external
async login(@requestBody() credentials: Credentials) {
    if (!credentials.username || !credentials.password) throw new HttpErrors.BadRequest('Missing Username or Password');
    const user = await this.userRepository.findOne({where: {id: credentials.username}});
    if (!user) throw new HttpErrors.Unauthorized('Invalid credentials');

    const isPasswordMatched = user.password === credentials.password;
    if (!isPasswordMatched) throw new HttpErrors.Unauthorized('Invalid credentials');

    const tokenObject = {username: credentials.username};
    const token = await signAsync(tokenObject, JWT_SECRET);
    const roles = await this.userRoleRepository.find({where: {userId: user.id}});
    const {id, email} = user;

    return {
      token,
      id: id as string,
      email,
      roles: roles.map(r => r.roleId),
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / shopping-cart.controller.ts View on Github external
async set(
    @param.path.string('userId') userId: string,
    @requestBody({description: 'shopping cart'}) cart: ShoppingCart,
  ): Promise {
    debug('Create shopping cart %s: %j', userId, cart);
    if (userId !== cart.userId) {
      throw new HttpErrors.BadRequest(
        `User id does not match: ${userId} !== ${cart.userId}`,
      );
    }
    await this.shoppingCartRepository.set(userId, cart);
  }
github gobackhuoxing / first-web-game-lb4 / firstgame / src / controllers / character.controller.ts View on Github external
async create(
    @requestBody(UserRequestBody) character: Character,
  ): Promise {
    character.permissions = [
      PermissionKey.ViewOwnUser,
      PermissionKey.CreateUser,
      PermissionKey.UpdateOwnUser,
      PermissionKey.DeleteOwnUser,
    ];
    if (await this.characterRepository.exists(character.email)) {
      throw new HttpErrors.BadRequest(`This email already exists`);
    } else {
      const savedCharacter = await this.characterRepository.create(character);
      delete savedCharacter.password;
      return savedCharacter;
    }
  }
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
async loginWithClientUser(
    @requestBody() req: LoginRequest,
  ): Promise {
    if (!this.client || !this.user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    } else if (!this.client.userIds || this.client.userIds.length === 0) {
      throw new HttpErrors.UnprocessableEntity(AuthErrorKeys.ClientUserMissing);
    } else if (!req.client_secret) {
      throw new HttpErrors.BadRequest(AuthErrorKeys.ClientSecretMissing);
    }
    try {
      const payload: ClientAuthCode = {
        clientId: this.client.clientId,
        user: this.user,
      };
      return await this.createJWT(payload, this.client);
    } catch (error) {
      throw new HttpErrors.InternalServerError(
        AuthErrorKeys.InvalidCredentials,
      );
    }
  }