How to use @hapi/boom - 10 common examples

To help you get started, we’ve selected a few @hapi/boom 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 hapijs / hapi / test / auth.js View on Github external
}

            const parts = authorization.split(/\s+/);
            if (parts.length !== 2) {
                return h.continue;          // Error without error or credentials
            }

            const username = parts[1];
            const credentials = settings.users[username];

            if (!credentials) {
                throw Boom.unauthorized('Missing credentials', 'Custom');
            }

            if (credentials === 'skip') {
                return h.unauthenticated(Boom.unauthorized(null, 'Custom'));
            }

            if (typeof credentials === 'string') {
                return h.response(credentials).takeover();
            }

            credentials.user = credentials.user || null;
            return h.authenticated({ credentials, artifacts: settings.artifacts });
        },
        response: (request, h) => {
github JKHeadley / rest-hapi / tests / unit / enforce-document-scope.tests.js View on Github external
const docs = request.response.source.docs
      // 

      // 
      let result
      try {
        result = enforceDocumentScopePostForModel(request, h)
      } catch (err) {
        result = err
      }
      // 

      // 
      t.deepEqual(
        result,
        Boom.forbidden('Insufficient document scope.'),
        'boom error thrown'
      )
      // 

      // 
      // 
    })
  )
github hapijs / statehood / lib / index.js View on Github external
// Contextualize definition

            if (definition.contextualize) {
                if (definition === base) {
                    definition = Hoek.clone(definition);
                }

                await definition.contextualize(definition, context);
            }

            // Validate name

            const nameRx = definition.strictHeader ? internals.validateRx.nameRx.strict : internals.validateRx.nameRx.loose;
            if (!nameRx.test(cookie.name)) {
                throw Boom.badImplementation('Invalid cookie name: ' + cookie.name);
            }

            // Prepare value (encode, sign)

            const value = await exports.prepareValue(cookie.name, cookie.value, definition);

            // Validate prepared value

            const valueRx = definition.strictHeader ? internals.validateRx.valueRx.strict : internals.validateRx.valueRx.loose;
            if (value &&
                (typeof value !== 'string' || !value.match(valueRx))) {

                throw Boom.badImplementation('Invalid cookie value: ' + cookie.value);
            }

            // Construct cookie
github elitan / hasura-backend-plus / src / auth / auth.js View on Github external
}
    ) {
      affected_rows
    }
  }
  `;

  let hasura_data;
  try {
    hasura_data = await graphql_client.request(mutation, {
      user_id: user.id,
    });
  } catch (e) {
    console.error(e);
    // console.error('Error connection to GraphQL');
    return next(Boom.unauthorized('Unable to delete refresh token'));
  }

  res.send('OK');
});
github opporty-com / Plasma-Cash / plasma-core / src / api / helpers / index.js View on Github external
async function failActionResponse(request, h, err) {
  if (process.env.NODE_ENV === 'production') {
    // In prod, log a limited error message and throw the default Bad Request error.
    console.error('ValidationError:', err.message);
    throw Boom.badGateway(`Invalid response data`);
  }
  // During development, log and respond with the full error.
  console.error('ResponseError:', err);
  const error = Boom.badGateway(`Invalid response data`);
  error.reformat();

  error.output.payload.details = err.details;
  throw error;

}
github opporty-com / Plasma-Cash / plasma-core / src / api / helpers / index.js View on Github external
async function failActionResponse(request, h, err) {
  if (process.env.NODE_ENV === 'production') {
    // In prod, log a limited error message and throw the default Bad Request error.
    console.error('ValidationError:', err.message);
    throw Boom.badGateway(`Invalid response data`);
  }
  // During development, log and respond with the full error.
  console.error('ResponseError:', err);
  const error = Boom.badGateway(`Invalid response data`);
  error.reformat();

  error.output.payload.details = err.details;
  throw error;

}
github hapijs / iron / lib / index.js View on Github external
exports.unseal = async function (sealed, password, options) {

    options = Object.assign({}, options);                                       // Shallow cloned to prevent changes during async operations

    const now = Date.now() + (options.localtimeOffsetMsec || 0);                // Measure now before any other processing

    // Break string into components

    const parts = sealed.split('*');
    if (parts.length !== 8) {
        throw new Boom.Boom('Incorrect number of sealed components');
    }

    const macPrefix = parts[0];
    const passwordId = parts[1];
    const encryptionSalt = parts[2];
    const encryptionIv = parts[3];
    const encryptedB64 = parts[4];
    const expiration = parts[5];
    const hmacSalt = parts[6];
    const hmac = parts[7];
    const macBaseString = macPrefix + '*' + passwordId + '*' + encryptionSalt + '*' + encryptionIv + '*' + encryptedB64 + '*' + expiration;

    // Check prefix

    if (macPrefix !== exports.macPrefix) {
        throw new Boom.Boom('Wrong mac prefix');
github elitan / hasura-backend-plus / src / auth / auth.js View on Github external
router.post('/refresh-token', async (req, res, next) => {

  // validate username and password
  const schema = Joi.object().keys({
    refresh_token: Joi.string().required(),
  });

  const { error, value } = schema.validate(req.body);

  if (error) {
    return next(Boom.badRequest(error.details[0].message));
  }

  const { refresh_token } = value;

  let query = `
  query get_refresh_token(
    $refresh_token: uuid!,
    $current_timestampz: timestamptz!,
  ) {
    refresh_tokens: ${schema_name}refresh_tokens (
      where: {
        _and: [{
          refresh_token: { _eq: $refresh_token }
        }, {
          user: { active: { _eq: true }}
        }, {
github ipfs / js-ipfs / src / http / api / resources / files-regular.js View on Github external
handler (request, h) {
    const { ipfs } = request.server.app
    const { key } = request.pre.args

    const options = {
      recursive: request.query.recursive,
      format: request.query.format,
      edges: request.query.edges,
      unique: request.query.unique,
      maxDepth: request.query['max-depth']
    }

    // have to do this here otherwise the validation error appears in the stream tail and
    // this doesn't work in browsers: https://github.com/ipfs/js-ipfs/issues/2519
    if (options.edges && options.format !== Format.default) {
      throw Boom.badRequest('Cannot set edges to true and also specify format')
    }

    return streamResponse(request, h, async (output) => {
      for await (const ref of ipfs._refsAsyncIterator(key, options)) {
        output.write(
          JSON.stringify({
            Ref: ref.ref,
            Err: ref.err
          }) + '\n'
        )
      }
    })
  }
}
github hapijs / nes / lib / socket.js View on Github external
internals.Socket.prototype._authenticate = async function (request) {

    await this._authByCookie();

    if (!request.auth &&
        !this.auth.isAuthenticated &&
        this._listener._authRequired()) {

        throw Boom.unauthorized('Connection requires authentication');
    }

    if (request.auth &&
        request.type !== 'reauth' &&
        this.auth.isAuthenticated) {        // Authenticated using a cookie during upgrade

        throw Boom.badRequest('Connection already authenticated');
    }

    clearTimeout(this.auth._initialAuthTimeout);
    this.auth._initialAuthTimeout = null;

    if (request.auth) {
        const config = this._listener._settings.auth;
        if (config.type === 'direct') {
            const route = this.server.lookup(config.id);
            request.auth.headers = request.auth.headers || {};
            request.auth.headers['x-forwarded-for'] = this.info['x-forwarded-for'];
            const res = await this.server.inject({ url: route.path, method: 'auth', headers: request.auth.headers, remoteAddress: this.info.remoteAddress, allowInternals: true, validate: false });
            if (res.statusCode !== 200) {
                throw Boom.unauthorized(res.result.message);
            }