How to use the routing-controllers.HttpError function in routing-controllers

To help you get started, we’ve selected a few routing-controllers 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 youzan / zan-proxy / src / core / services / host.ts View on Github external
public async create(hostFile: IHostFile) {
    const { name, description, content = {} } = hostFile;
    if (this.exist(name)) {
      // 文件已经存在,无法创建
      throw new HttpError(409, 'Host规则已存在');
    }

    const entity: IHostFile = {
      name,
      meta: {
        local: true,
      },
      description,
      checked: false,
      content,
    };
    this.hostFilesMap[name] = entity;

    await this.saveHostFile(name, entity);
  }
github jmaicaaan / express-starter-ts / src / middlewares / authorization.checker.ts View on Github external
const user = await userRepository.getUserByToken(token);
      const userRoles = await userRepository.getUserRolesById(user.id);

      const isAuthorized = userRoles.find((role) => roles.indexOf(role.name) > -1) ? true : false;

      return isAuthorized;
    } else {
      // check only if token is existing in the request
      if (token) {
        return true;
      }
      return false;
    }
  } catch (error) {
    throw new HttpError(403, error.message);
  }
}
github youzan / zan-proxy / src / core / services / rule.ts View on Github external
public async updateRuleInfo(
    originName: string,
    {
      name,
      description,
    }: {
      name: string;
      description: string;
    },
  ) {
    if (name !== originName && this.rules[name]) {
      throw new HttpError(409, '规则集名称已存在');
    }

    const ruleFile = this.rules[originName];
    if (name !== originName) {
      await this.deleteRuleFile(originName);
    }

    // 修改 rule 内容
    ruleFile.name = name;
    ruleFile.description = description;
    await this.saveRuleFile(name, ruleFile);
  }
github geli-lms / geli / api / src / controllers / UserController.ts View on Github external
.then((adminUsers) => {
        console.log('AdminUsers: ' + adminUsers.length);
        const _id = adminUsers[0]._id;
        const idTest = adminUsers[0].get('id');
        if (adminUsers.length === 1 &&
            adminUsers[0].get('id') === id &&
            adminUsers[0].role === 'admin' &&
            user.role !== 'admin') {
          throw new HttpError(400, 'There are no other users with admin privileges.');
        } else {
          return User.findByIdAndUpdate(id, user, {'new': true});
        }
      })
      .then((savedUser) => savedUser.toObject());
github geli-lms / geli / api / src / controllers / ObsCsvController.ts View on Github external
userLines.forEach((singleLine) => {
        actualLine++;
        const lastName = singleLine.split(';')[0];
        const firstName = singleLine.split(';')[1];
        const uid = singleLine.split(';')[2];
        if (firstName.length > 0 && lastName.length > 0 && uid.length > 0) {
          if (!isNaN(Number(firstName))) {
            throw new HttpError(400, 'First name was a number in line ' + actualLine + '.');
          }
          if (!isNaN(Number(lastName))) {
            throw new HttpError(400, 'Last name was a number in line ' + actualLine + '.');
          }
          if (isNaN(Number(uid))) {
            throw new HttpError(400, 'UID is not a number ' + actualLine + '.');
          }
          this.whitelistUser.push({
            firstName: firstName,
            lastName: lastName,
            uid: uid
          });
        }
      }
    );
github geli-lms / geli / api / src / controllers / AuthController.ts View on Github external
.then((existingUser) => {
        if (!existingUser) {
          throw new HttpError(422, 'could not reset users password');
        }
        if (existingUser.resetPasswordExpires < new Date()) {
          throw new ForbiddenError('your reset password token is expired');
        }

        existingUser.password = newPassword;
        existingUser.resetPasswordToken = undefined;
        existingUser.resetPasswordExpires = undefined;
        existingUser.markModified('password');
        return existingUser.save();
      })
      .then((savedUser) => {
github geli-lms / geli / api / src / controllers / AuthController.ts View on Github external
.then((existingUser) => {
        if (!existingUser) {
          throw new HttpError(422, 'could not activate user');
        }

        existingUser.authenticationToken = undefined;
        existingUser.isActive = true;
        return existingUser.save();
      })
      .then((user) => {
github bitwit / typescript-express-api-template / api / controllers / MainController.ts View on Github external
async login(@Body() credentials: LoginBody) {

        try {
            const user = await User.findOne({ where: { email: credentials.email } })
            let matches = await bcrypt.compare(credentials.password, user.password)
            if (!matches) {
                throw new Error()
            }
            let authToken = new AuthToken()
            authToken.user = user
            await authToken.save()
            return AuthToken.findOne({ token: authToken.token })
        } catch {
            throw new HttpError(400, "Credentials do not match")
        }

    }
}
github youzan / zan-proxy / src / core / services / rule.ts View on Github external
public async create(name: string, description: string) {
    if (this.exist(name)) {
      throw new HttpError(409, '规则集名称已存在');
    }

    const ruleFile: IRuleFile = {
      name,
      meta: {
        remote: false,
        url: '',
      },
      description,
      checked: false,
      content: [],
    };
    await this.saveRuleFile(name, ruleFile);
  }
github geli-lms / geli / api / src / controllers / AuthController.ts View on Github external
@Res() response: Response) {
        const user = await User.findOne({'profile.lastName': lastname, uid: uid, role: 'student'});

        if (!user) {
          throw new BadRequestError(errorCodes.errorCodes.user.userNotFound.code);
        }

        if (user.isActive) {
          throw new BadRequestError(errorCodes.errorCodes.user.userAlreadyActive.code);
        }

        const timeSinceUpdate: number = (Date.now() - user.updatedAt.getTime() ) / 60000;
        if (timeSinceUpdate < Number(config.timeTilNextActivationResendMin)) {
          const retryAfter: number = (Number(config.timeTilNextActivationResendMin) - timeSinceUpdate) * 60;
          response.set('retry-after', retryAfter.toString());
          throw new HttpError(503, errorCodes.errorCodes.user.retryAfter.code);
        }

        const existingUser = await User.findOne({email: email});
        if (existingUser && existingUser.uid !== uid) {
          throw new BadRequestError(errorCodes.errorCodes.mail.duplicate.code);
        }

        user.authenticationToken = undefined;
        user.email = email;
        const savedUser = await user.save();

        try {
          await emailService.resendActivation(savedUser);
        } catch (err) {
          throw new InternalServerError(err.toString());
        }