How to use the api/utils.createError function in api

To help you get started, we’ve selected a few api 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 huridocs / uwazi / app / api / users / specs / users.spec.js View on Github external
it('should throw error if code is incorrect', async () => {
      try {
        await createUserAndTestUnlock('someruser1', 'incorrect');
        fail('should throw error');
      } catch (e) {
        expect(e).toEqual(createError('Invalid username or unlock code', 403));
        const [user] = await users.get({ username: 'someuser1' }, '+accountLocked +accountUnlockCode +failedLogins');
        expect(user.accountLocked).toBe(true);
        expect(user.accountUnlockCode).toBe('code');
      }
    });
  });
github huridocs / uwazi / app / api / utils / specs / handleError.spec.js View on Github external
it('should not show them in the log', () => {
      handleError(createError('test error', 400), { req: { body: { username: 'admin', password: '1234' } } });
      expect(debugLog.debug.calls.allArgs()).toMatchSnapshot();
    });
  });
github huridocs / uwazi / app / api / users / users.js View on Github external
async save(user, currentUser) {
    const [userInTheDatabase] = await model.get({ _id: user._id }, '+password');

    if (user._id === currentUser._id.toString() && user.role !== currentUser.role) {
      return Promise.reject(createError('Can not change your own role', 403));
    }

    if (user.hasOwnProperty('role') && user.role !== userInTheDatabase.role && currentUser.role !== 'admin') {
      return Promise.reject(createError('Unauthorized', 403));
    }

    return model.save({
      ...user,
      password: user.password ? await encryptPassword(user.password) : userInTheDatabase.password,
    });
  },
github huridocs / uwazi / app / api / relationships / relationships.js View on Github external
async save(_relationships, language) {
    if (!language) {
      throw createError('Language cant be undefined');
    }

    const relationships = !Array.isArray(_relationships) ? [_relationships] : _relationships;

    if (relationships.length === 1 && !relationships[0].hub) {
      throw createError('Single relationships must have a hub');
    }

    const hub = relationships[0].hub || generateID();

    const result = await Promise.all(relationships.map((relationship) => {
      const action = relationship._id ? updateRelationship : createRelationship;

      return action({ ...relationship, hub }, language)
      .then(savedRelationship => Promise.all([savedRelationship, entities.getById(savedRelationship.entity, language)]))
      .then(([savedRelationship, connectedEntity]) => normalizeConnectedDocumentData(savedRelationship, connectedEntity));
github huridocs / uwazi / app / api / users / users.js View on Github external
delete(_id, currentUser) {
    if (_id === currentUser._id.toString()) {
      return Promise.reject(createError('Can not delete yourself', 403));
    }

    return model.count()
    .then((count) => {
      if (count > 1) {
        return model.delete({ _id });
      }

      return Promise.reject(createError('Can not delete last user', 403));
    });
  },
  async login({ username, password }, domain) {
github huridocs / uwazi / app / api / users / users.js View on Github external
async login({ username, password }, domain) {
    const [user] = await this.get({ username }, '+password +accountLocked +failedLogins +accountUnlockCode');
    if (!user) {
      throw createError('Invalid username or password', 401);
    }
    if (user.accountLocked) {
      throw createError('Account locked. Check your email to unlock.', 403);
    }

    const passwordValidated = await comparePasswords(password, user.password);
    const oldPasswordValidated = user.password === SHA256(password).toString();

    if (oldPasswordValidated) {
      await model.save({ _id: user._id, password: await encryptPassword(password) });
    }

    if (!oldPasswordValidated && !passwordValidated) {
      const updatedUser = await model.db.findOneAndUpdate({ _id: user._id },
          { $inc: { failedLogins: 1 } }, { new: true, fields: '+failedLogins' });
      if (updatedUser.failedLogins >= MAX_FAILED_LOGIN_ATTEMPTS) {
github huridocs / uwazi / app / api / relationships / relationships.js View on Github external
async save(_relationships, language) {
    if (!language) {
      throw createError('Language cant be undefined');
    }

    const relationships = !Array.isArray(_relationships) ? [_relationships] : _relationships;

    if (relationships.length === 1 && !relationships[0].hub) {
      throw createError('Single relationships must have a hub');
    }

    const hub = relationships[0].hub || generateID();

    const result = await Promise.all(relationships.map((relationship) => {
      const action = relationship._id ? updateRelationship : createRelationship;

      return action({ ...relationship, hub }, language)
      .then(savedRelationship => Promise.all([savedRelationship, entities.getById(savedRelationship.entity, language)]))
      .then(([savedRelationship, connectedEntity]) => normalizeConnectedDocumentData(savedRelationship, connectedEntity));
    }));

    await this.updateEntitiesMetadataByHub(hub, language);
    return result;
  },
github huridocs / uwazi / app / api / users / specs / users.spec.js View on Github external
.catch((error) => {
          expect(error).toEqual(createError('Can not change your own role', 403));
          done();
        })
        .catch(catchErrors(done));
github huridocs / uwazi / app / api / users / specs / users.spec.js View on Github external
.catch((error) => {
          expect(error).toEqual(createError('Username already exists', 409));
          done();
        });
      });
github huridocs / uwazi / app / api / auth2fa / usersUtils.ts View on Github external
export const setSecret = async (user: User) => {
  const dbUser = await getUser({ _id: user._id });
  const siteName = await conformSiteName();
  const secret = otplib.authenticator.generateSecret();
  const otpauth = otplib.authenticator.keyuri(dbUser.username || '', siteName, secret);

  if (!dbUser.using2fa) {
    await usersModel.save({ _id: dbUser._id, secret });
    return { secret, otpauth };
  }

  throw createError('Unauthorized', 401);
};