How to use the @hapi/boom.forbidden function in @hapi/boom

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 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 dherault / serverless-offline / src / events / http / createAuthScheme.js View on Github external
const lambdaFunction = lambda.get(authFunName)
      lambdaFunction.setEvent(event)

      try {
        const result = await lambdaFunction.runHandler()

        // return processResponse(null, result)
        const policy = result

        // Validate that the policy document has the principalId set
        if (!policy.principalId) {
          serverlessLog(
            `Authorization response did not include a principalId: (λ: ${authFunName})`,
          )

          return Boom.forbidden('No principalId set on the Response')
        }

        if (!authCanExecuteResource(policy.policyDocument, event.methodArn)) {
          serverlessLog(
            `Authorization response didn't authorize user to access resource: (λ: ${authFunName})`,
          )

          return Boom.forbidden(
            'User is not authorized to access this resource',
          )
        }

        serverlessLog(
          `Authorization function returned a successful response: (λ: ${authFunName})`,
        )
github hapijs / nes / lib / listener.js View on Github external
}
            }

            // Check entity

            const entity = auth.entity || 'any';
            if (entity === 'user' &&
                !credentials.user) {

                throw Boom.forbidden('Application credentials cannot be used on a user subscription');
            }

            if (entity === 'app' &&
                credentials.user) {

                throw Boom.forbidden('User credentials cannot be used on an application subscription');
            }
        }
        else if (auth.mode === 'required') {
            throw Boom.unauthorized('Authentication required to subscribe');
        }
    }

    await match.route.subscribers.add(socket, path, match);
    socket._subscriptions[path] = match.route.subscribers;
};
github hapijs / hapi / lib / auth.js View on Github external
_access(request, route) {

        const config = this.lookup(route || request.route);
        if (!config ||
            !config.access) {

            return true;
        }

        const credentials = request.auth.credentials;
        if (!credentials) {
            if (config.mode !== 'required') {
                return false;
            }

            throw Boom.forbidden('Request is unauthenticated');
        }

        const requestEntity = (credentials.user ? 'user' : 'app');

        const scopeErrors = [];
        for (const access of config.access) {

            // Check entity

            const entity = access.entity;
            if (entity &&
                entity !== 'any' &&
                entity !== requestEntity) {

                continue;
            }
github dherault / serverless-offline / src / events / http / createAuthScheme.js View on Github external
// Validate that the policy document has the principalId set
        if (!policy.principalId) {
          serverlessLog(
            `Authorization response did not include a principalId: (λ: ${authFunName})`,
          )

          return Boom.forbidden('No principalId set on the Response')
        }

        if (!authCanExecuteResource(policy.policyDocument, event.methodArn)) {
          serverlessLog(
            `Authorization response didn't authorize user to access resource: (λ: ${authFunName})`,
          )

          return Boom.forbidden(
            'User is not authorized to access this resource',
          )
        }

        serverlessLog(
          `Authorization function returned a successful response: (λ: ${authFunName})`,
        )

        const authorizer = {
          integrationLatency: '42',
          principalId: policy.principalId,
          ...policy.context,
        }

        // Set the credentials for the rest of the pipeline
        // return resolve(
github JKHeadley / rest-hapi / policies / enforce-document-scope.js View on Github external
if (request.response.source.docs) {
            result = internals.verifyScope(
              request.response.source.docs,
              'read',
              userScope,
              Log
            )
          } else {
            result = { authorized: true }
          }
        }

        if (result.authorized) {
          return h.continue
        } else if (request.params._id || config.enableDocumentScopeFail) {
          throw Boom.forbidden('Insufficient document scope.')
        } else {
          let unauthorizedIds = result.unauthorizedDocs.map(function(document) {
            return document._id.toString()
          })
          // EXPL: replace unauthorized docs with an error
          request.response.source.docs = request.response.source.docs.map(
            function(document) {
              if (unauthorizedIds.indexOf(document._id.toString()) < 0) {
                return document
              } else {
                return { error: 'Insufficient document scope.' }
              }
            }
          )

          return h.continue
github hapijs / hapi / lib / auth.js View on Github external
!internals.validateScope(credentials, scope, 'selection') ||
                    !internals.validateScope(credentials, scope, 'forbidden')) {

                    scopeErrors.push(scope);
                    continue;
                }
            }

            return true;
        }

        // Scope error

        if (scopeErrors.length) {
            request._log(['auth', 'scope', 'error']);
            throw Boom.forbidden('Insufficient scope', { got: credentials.scope, need: scopeErrors });
        }

        // Entity error

        if (requestEntity === 'app') {
            request._log(['auth', 'entity', 'user', 'error']);
            throw Boom.forbidden('Application credentials cannot be used on a user endpoint');
        }

        request._log(['auth', 'entity', 'app', 'error']);
        throw Boom.forbidden('User credentials cannot be used on an application endpoint');
    }
github hapijs / nes / lib / listener.js View on Github external
// Check scope

            if (auth.scope) {
                let scopes = auth.scope;
                if (auth.hasScopeParameters) {
                    scopes = [];
                    const context = { params: match.params };
                    for (let i = 0; i < auth.scope.length; ++i) {
                        scopes[i] = Hoek.reachTemplate(context, auth.scope[i]);
                    }
                }

                if (!credentials.scope ||
                    (typeof credentials.scope === 'string' ? !scopes.includes(credentials.scope) : !Hoek.intersect(scopes, credentials.scope).length)) {

                    throw Boom.forbidden('Insufficient scope to subscribe, expected any of: ' + scopes);
                }
            }

            // Check entity

            const entity = auth.entity || 'any';
            if (entity === 'user' &&
                !credentials.user) {

                throw Boom.forbidden('Application credentials cannot be used on a user subscription');
            }

            if (entity === 'app' &&
                credentials.user) {

                throw Boom.forbidden('User credentials cannot be used on an application subscription');
github hapijs / h2o2 / test / index.js View on Github external
const onResponseWithError = function (err, res, request, h, settings, ttl) {

            expect(err).to.be.null();
            throw Boom.forbidden('Forbidden');
        };
github nearform / udaru / packages / udaru-hapi-plugin / lib / authentication.js View on Github external
async function authorize (job) {
  const resources = await buildResources(job.options, job.udaru, job.authParams, job.request, job.organizationId)

  const action = job.authParams.action
  const userId = job.currentUser.id
  const organizationId = job.currentUser.organizationId

  const valids = await Promise.all(resources.map(resource => checkAuthorization(job.udaru, userId, action, organizationId, resource)))

  if (!valids.includes(true)) throw Boom.forbidden('Invalid credentials', 'udaru')
}