geocoding.geocode(`${request.payload.location.street}, ${request.payload.location.city}, France`, (err, location) => {
      if (err || !location) {
        reply(Boom.badImplementation(err));
      } else {
        const coordinates = [location.lng, location.lat];

        // création d'un foodkeeper
        const foodkeeper = new Foodkeepers();
        foodkeeper.name = request.payload.name;
        foodkeeper.description = request.payload.description;
        foodkeeper.picture = request.payload.picture;
        foodkeeper.location.street = request.payload.location.street;
        foodkeeper.location.number = request.payload.location.number;
        foodkeeper.location.apartment = request.payload.location.apartment;
        foodkeeper.location.floor = request.payload.location.floor;
        foodkeeper.location.additional = request.payload.location.additional;
        foodkeeper.location.infos = request.payload.location.infos;
        foodkeeper.location.city = request.payload.location.city;
        foodkeeper.location.zipcode = request.payload.location.zipcode;
        foodkeeper.location.coordinates = coordinates;

        // on sauvegarde les données
        foodkeeper.save()
          .then((response) => {
            // lier le garde manger à l'utilisateur
            Users.findByIdAndUpdate(request.payload.userId,
              { $push: { 'foodkeepers': { _id: response._id } } },
              { safe: true, upsert: true, new: true }
            )
            .then(() => reply({ statusCode: 200, message: 'Successfully created' }))
            .catch(error => reply(Boom.badImplementation(error)));
          })
          .catch(error => reply(Boom.badImplementation(error)));
      }
    });
      Reading.count({ sensorId: sensor.id, time: { $gte: fromTime, $lte: toTime } }, function (err, finalVolume) {
        if (err) {
          return reply(Boom.badImplementation(err));
        }

        Sensor.find({ roadId: id, kilometer: { $gte: fromKm } }, { _id: 1 }, { sort: { kilometer: 1 }, limit: 1 }, function (err, docs) {
          if (err) {
            return reply(Boom.badImplementation(err));
          }

          if (!docs.length) {
            return reply(Boom.notFound('Cannot find sensor near fromKm'));
          }

          var sensor = docs[0];
          Reading.count({ sensorId: sensor.id, time: { $gte: fromTime, $lte: toTime } }, function (err, initialVolume) {
            if (err) {
              return reply(Boom.badImplementation(err));
            }

            reply(finalVolume - initialVolume);
          });
        });
      });
 Influencer.getAllInfluencer({"aboutMe": { $exists: true }}, function(err, result) {
   //console.log(result);
     if (!err) {
         result.forEach(function (influencer) {
           if(influencer.instagramId){ 
             if(influencer.accesstoken !== undefined){     
               var params = { access_token: influencer.accesstoken };
               //code to update the user profile image if it is changed
               var job = queue.create(randomQueue, {
                   params: params
                 , instagramId: influencer.instagramId
                 , usertype: 'Influencer'
               
               }).removeOnComplete( true ).save( function(err){
                                          //if( !err ) console.log(job.id );
                });
             }
           }
         
         });
     } else {
         return res.send(Boom.badImplementation(err)); // 500 error
     }
 });
Example #4
0
                        .then((result) => {
                          // console.log('social register: user create result: ', result);

                          if (result[0] !== undefined && result[0] !== null) {
                            //Error
                            console.log('ajv error', result, co.parseAjvValidationErrors(result));
                            return res(boom.badData('registration failed because data is wrong: ', co.parseAjvValidationErrors(result)));
                          }

                          if (result.insertedCount === 1) {
                            //success
                            user._id = result.insertedId;

                            return res({
                              userid: result.insertedId,
                              username: user.username,
                              access_token: 'dummy',
                              expires_in: 0
                            })
                              .header(config.JWT.HEADER, jwt.createToken(user));
                          }

                          res(boom.badImplementation());
                        })
Example #5
0
        .catch(function(err) {

            // PL/pgSQL Error "no_data_found"; 
            // this will happen when the we try to update an initiative that has been deleted meanwhile
            // (or that was never created)
            if(err.code === "P0002"){
                err = Boom.notFound("The resource does not exist.");
            }

            // PL/pgSQL Error "unique_violation"; 
            // this will happen when we try to update (insert?) a row with a repeated slug (already 
            // present in some other project)
            if(err.code === "23505"){
                if(err.detail.indexOf("slug") >= 0){
                    err = Boom.conflict("The provided value for slug is already in use by other initiative. Please choose a different slug.");
                }
                else{
                    err = Boom.conflict();
                }
            }

            err = err.isBoom ? err : Boom.badImplementation(Utils.getErrMsg(err));
            return done(err);
        });
Example #6
0
		it("succeeds", function () {
			expect(Boom.badImplementation()).to.be.a.serverError;
		});
Example #7
0
 Item.find({tag:request.params.tag}, function (err, items) {
   if (!err) {
     return reply(items);
   }
   return reply(Boom.badImplementation(err)); // 500 error
 });
Example #8
0
 out.on('error', function (err) { 
   return reply(Boom.badImplementation(err));
 });
Example #9
0
 Item.distinct('tags').exec(function(err, tags) {
   if (!err) {
     return reply(tags);
   }
   return reply(Boom.badImplementation(err)); // 500 error
 });
Example #10
0
File: index.js Project: Zeetah/hapi
    var validate = function (err, credentials, options) {

        options = options || {};

        // Unauthenticated

        if (!err && !credentials) {
            return next(Boom.badImplementation('Authentication response missing both error and credentials'));
        }

        if (err) {
            if (options.log) {
                request.log(['hapi', 'auth', 'error', config.strategies[strategyPos]].concat(options.log.tags), options.log.data);
            }
            else {
                request.log(['hapi', 'auth', 'unauthenticated'], err);
            }

            if (err instanceof Error === false ||                                   // Not an actual error (e.g. redirect, custom response)
                !err.isMissing ||                                                   // Missing authentication (did not fail)
                err.response.code !== 401) {                                        // An actual error (not just missing authentication)

                if (config.mode === 'try') {
                    request.auth.isAuthenticated = false;
                    request.auth.credentials = credentials;
                    request.auth.artifacts = options.artifacts;
                    request.log(['hapi', 'auth', 'unauthenticated', 'try'], err);
                    return next();
                }

                return next(err);
            }

            // Try next strategy

            if (err.response.headers['WWW-Authenticate']) {
                authErrors.push(err.response.headers['WWW-Authenticate']);
            }

            return authenticate();
        }

        // Authenticated

        request.auth.credentials = credentials;
        request.auth.artifacts = options.artifacts;
        request.auth._strategy = self._strategies[config.strategies[strategyPos - 1]];

        // Check scope

        if (config.scope) {
            if (!credentials ||                                                                                         // Missing credentials
                !credentials.scope ||                                                                                   // Credentials missing scope
                (typeof config.scope === 'string' && credentials.scope.indexOf(config.scope) === -1) ||                 // String scope isn't in credentials
                !Utils.intersect(config.scope, credentials.scope).length) {                                             // Array scope doesn't intersect credentials

                request.log(['hapi', 'auth', 'scope', 'error'], { got: credentials && credentials.scope, need: config.scope });
                return next(Boom.forbidden('Insufficient scope - ' + config.scope + ' expected'));
            }
        }

        // Check TOS

        var tos = (config.hasOwnProperty('tos') ? config.tos : false);
        if (tos &&
            (!credentials || !credentials.tos || !Semver.satisfies(credentials.tos, tos))) {

            request.log(['hapi', 'auth', 'tos', 'error'], { min: tos, received: credentials && credentials.tos });
            return next(Boom.forbidden('Insufficient TOS accepted'));
        }

        // Check entity

        var entity = config.entity || 'any';

        // Entity: 'any'

        if (entity === 'any') {
            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'user'

        if (entity === 'user') {
            if (!credentials || !credentials.user) {
                request.log(['hapi', 'auth', 'error'], 'User credentials required');
                return next(Boom.forbidden('Application credentials cannot be used on a user endpoint'));
            }

            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'app'

        if (credentials && credentials.user) {
            request.log(['hapi', 'auth', 'error'], 'App credentials required');
            return next(Boom.forbidden('User credentials cannot be used on an application endpoint'));
        }

        request.log(['hapi', 'auth']);
        request.auth.isAuthenticated = true;
        return next();
    };
Example #11
0
 item.remove(function (err) {
     if (err) { reply(Boom.badImplementation(err.message)); }
     reply({ success : true });
 });
Example #12
0
    var validate = function (err, strategy, result) {           // err can be Boom, Error, or a valid response object

        if (!strategy) {
            return next(err);
        }

        result = result || {};

        // Unauthenticated

        if (!err && !result.credentials) {
            return next(Boom.badImplementation('Authentication response missing both error and credentials'));
        }

        if (err) {
            if (err instanceof Error === false) {
                request.log(['hapi', 'auth', 'response', 'unauthenticated'], err.statusCode);
                return next(err);
            }

            if (result.log) {
                request.log(['hapi', 'auth', 'error', strategy].concat(result.log.tags), result.log.data);
            }
            else {
                request.log(['hapi', 'auth', 'error', 'unauthenticated'], err);
            }

            if (err.isMissing) {

                // Try next strategy

                authErrors.push(err.output.headers['WWW-Authenticate']);
                return authenticate();
            }

            if (config.mode === 'try') {
                request.auth.isAuthenticated = false;
                request.auth.strategy = strategy;
                request.auth.credentials = result.credentials;
                request.auth.artifacts = result.artifacts;
                request.auth.error = err;
                request.log(['hapi', 'auth', 'unauthenticated', 'try'], err);
                return next();
            }

            return next(err);
        }

        // Authenticated

        var credentials = result.credentials;
        request.auth.strategy = strategy;
        request.auth.credentials = credentials;
        request.auth.artifacts = result.artifacts;

        // Check scope

        if (config.scope) {
            if (!credentials.scope ||                                                                                   // Credentials missing scope
                (typeof config.scope === 'string' && credentials.scope.indexOf(config.scope) === -1) ||                 // String scope isn't in credentials
                (Array.isArray(config.scope) && !Hoek.intersect(config.scope, credentials.scope).length)) {            // Array scope doesn't intersect credentials

                request.log(['hapi', 'auth', 'scope', 'error'], { got: credentials.scope, need: config.scope });
                return next(Boom.forbidden('Insufficient scope - ' + config.scope + ' expected'));
            }
        }

        // Check TOS

        var tos = (config.hasOwnProperty('tos') ? config.tos : false);
        if (tos &&
            (!credentials.tos || !Semver.satisfies(credentials.tos, tos))) {

            request.log(['hapi', 'auth', 'tos', 'error'], { min: tos, received: credentials.tos });
            return next(Boom.forbidden('Insufficient TOS accepted'));
        }

        // Check entity

        var entity = config.entity || 'any';

        // Entity: 'any'

        if (entity === 'any') {
            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'user'

        if (entity === 'user') {
            if (!credentials.user) {
                request.log(['hapi', 'auth', 'error'], 'User credentials required');
                return next(Boom.forbidden('Application credentials cannot be used on a user endpoint'));
            }

            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'app'

        if (credentials.user) {
            request.log(['hapi', 'auth', 'error'], 'App credentials required');
            return next(Boom.forbidden('User credentials cannot be used on an application endpoint'));
        }

        request.log(['hapi', 'auth']);
        request.auth.isAuthenticated = true;
        return next();
    };
Example #13
0
async function addUser(agsssync, user) {
  const sheets = google.sheets('v4');
  const gsssync = await agsssync
    .populate('list user')
    .execPopulate();
  const authClient = agsssync.getAuthClient();
  // Find users
  const criteria = gsssync.getUserCriteria();
  if (Object.keys(criteria).length === 0) {
    throw Boom.unauthorized('You are not authorized to view this list');
  }
  const users = await User
    .find(criteria)
    .select(GSSSync.getUserAttributes())
    .sort('name')
    .lean();
  try {
    const column = await sheets.spreadsheets.values.get({
      spreadsheetId: gsssync.spreadsheet,
      range: 'A:A',
      auth: authClient,
    });
    if (!column || !column.data || !column.data.values) {
      throw Boom.badImplementation(`column or column.data.values is undefined on spreadsheet ${gsssync.spreadsheet}`);
    }
    let row = 0; let index = 0; let
      firstLine = true;
    column.data.values.forEach((elt) => {
      // Skip first line as it's the headers
      if (firstLine === true) {
        firstLine = false;
      } else {
        if (elt[0] !== users[row]._id.toString() && index === 0) {
          index = row + 1;
        }
        row += 1;
      }
    });
    if (index !== 0) {
      const body = {
        requests: [{
          insertDimension: {
            range: {
              sheetId: gsssync.sheetId,
              dimension: 'ROWS',
              startIndex: index,
              endIndex: index + 1,
            },
          },
        }],
      };
      await sheets.spreadsheets.batchUpdate({
        spreadsheetId: gsssync.spreadsheet,
        resource: body,
        auth: authClient,
      });
      const writeIndex = index + 1;
      await writeUser(gsssync, authClient, user, writeIndex);
    } else {
      throw Boom.badRequest('Could not add user');
    }
  } catch (err) {
    if (err.code === 404 || err.code === 403) {
      // Spreadsheet has been deleted, remove the synchronization
      gsssync.remove();
    }
  }
}
internals.Manager.prototype.render = function (filename, context, options, callback) {

    var self = this;

    context = context || {};
    options = options || {};

    var engine = null;

    var fileExtension = Path.extname(filename).slice(1);
    var extension = fileExtension || self._defaultExtension;
    if (!extension) {
        return callback(Boom.badImplementation('Unknown extension and no defaultExtension configured for view template: ' + filename));
    }

    engine = self._engines[extension];
    if (!engine) {
        return callback(Boom.badImplementation('No view engine found for file: ' + filename));
    }

    var settings = Utils.applyToDefaults(engine.config, options);

    var templatePath = this._path(filename + (fileExtension ? '' : engine.suffix), settings);
    if (templatePath.isBoom) {
        return callback(templatePath);
    }

    this._compile(templatePath, engine, settings, function (err, compiled) {

        if (err) {
            return callback(err);
        }

        // No layout

        if (!settings.layout) {
            compiled(context, settings.runtimeOptions, function (err, rendered) {

                if (err) {
                    return callback(Boom.badImplementation(err.message, err));
                }

                return callback(null, rendered, settings);
            });

            return;
        }

        // With layout

        if (context.hasOwnProperty(settings.layoutKeyword)) {
            return callback(Boom.badImplementation('settings.layoutKeyword conflict', { context: context, keyword: settings.layoutKeyword }));
        }

        var layoutPath = self._path((settings.layout === true ? 'layout' : settings.layout) + engine.suffix, settings, true);
        if (layoutPath.isBoom) {
            return callback(layoutPath);
        }

        self._compile(layoutPath, engine, settings, function (err, layout) {

            if (err) {
                return callback(err);
            }

            var layoutContext = Utils.clone(context);

            compiled(context, settings.runtimeOptions, function (err, rendered) {

                if (err) {
                    return callback(Boom.badImplementation(err.message, err));
                }

                layoutContext[settings.layoutKeyword] = rendered;

                layout(layoutContext, settings.runtimeOptions, function (err, rendered) {

                    if (err) {
                        return callback(Boom.badImplementation(err.message, err));
                    }

                    return callback(null, rendered, settings);
                });
            });
        });
    });
};
Example #15
0
File: auth.js Project: 4yu/hapi
    var validate = function (err, strategy, result) {           // err can be Boom, Error, or a valid response object

        if (!strategy) {
            return next(err);
        }

        result = result || {};

        // Unauthenticated

        if (!err && !result.credentials) {
            return next(Boom.badImplementation('Authentication response missing both error and credentials'));
        }

        if (err) {
            if (err instanceof Error === false) {
                request.log(['hapi', 'auth', 'response', 'unauthenticated'], err.statusCode);
                return next(err);
            }

            if (result.log) {
                request.log(['hapi', 'auth', 'error', strategy].concat(result.log.tags), result.log.data);
            }
            else {
                request.log(['hapi', 'auth', 'error', 'unauthenticated'], err);
            }

            if (err.isMissing) {

                // Try next strategy

                authErrors.push(err.output.headers['WWW-Authenticate']);
                return authenticate();
            }

            if (config.mode === 'try') {
                request.auth.isAuthenticated = false;
                request.auth.strategy = strategy;
                request.auth.credentials = result.credentials;
                request.auth.artifacts = result.artifacts;
                request.auth.error = err;
                request.log(['hapi', 'auth', 'unauthenticated', 'try'], err);
                return next();
            }

            return next(err);
        }

        // Authenticated

        var credentials = result.credentials;
        request.auth.strategy = strategy;
        request.auth.credentials = credentials;
        request.auth.artifacts = result.artifacts;

        // Check scope

        if (config.scope) {
            if (!credentials.scope ||
                (typeof config.scope === 'string' ?
                    (typeof credentials.scope === 'string' ? config.scope !== credentials.scope : credentials.scope.indexOf(config.scope) === -1) :
                    (typeof credentials.scope === 'string' ? config.scope.indexOf(credentials.scope) === -1 : !Hoek.intersect(config.scope, credentials.scope).length))) {

                request.log(['hapi', 'auth', 'scope', 'error'], { got: credentials.scope, need: config.scope });
                return next(Boom.forbidden('Insufficient scope, expected any of: ' + config.scope));
            }
        }

        // Check entity

        var entity = config.entity || 'any';

        // Entity: 'any'

        if (entity === 'any') {
            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'user'

        if (entity === 'user') {
            if (!credentials.user) {
                request.log(['hapi', 'auth', 'error'], 'User credentials required');
                return next(Boom.forbidden('Application credentials cannot be used on a user endpoint'));
            }

            request.log(['hapi', 'auth']);
            request.auth.isAuthenticated = true;
            return next();
        }

        // Entity: 'app'

        if (credentials.user) {
            request.log(['hapi', 'auth', 'error'], 'App credentials required');
            return next(Boom.forbidden('User credentials cannot be used on an application endpoint'));
        }

        request.log(['hapi', 'auth']);
        request.auth.isAuthenticated = true;
        return next();
    };
Example #16
0
 RateTypes.get([req.params.id, req.params.lang], function (err, result) {
     if (err) { reply(Boom.badImplementation(err.message)); }
     reply(result);
 });
Example #17
0
 }, function (err) {
     if (err) { reply(Boom.badImplementation(err.message)); }
     reply(item);
 });
Example #18
0
 .catch((err) => {
     return reply(Boom.badImplementation(err));
 });
Example #19
0
 RateTypes.find({"lang" : req.params.lang}, function (err, result) {
     if (err) { reply(Boom.badImplementation(err.message)); }
     reply(result);
 });
Example #20
0
internals.Manager.prototype.render = function (filename, context, options, callback) {

    var self = this;

    options = options || {};

    if (this._context) {
        var base = typeof this._context === 'function' ? this._context() : this._context;
        if (context) {
            base = Hoek.shallow(base);
            var keys = Object.keys(context);
            for (var i = 0, il = keys.length; i < il; ++i) {
                var key = keys[i];
                base[key] = context[key];
            }
        }

        context = base;
    }

    context = context || {};

    var engine = null;

    var fileExtension = Path.extname(filename).slice(1);
    var extension = fileExtension || this._defaultExtension;
    if (!extension) {
        return callback(Boom.badImplementation('Unknown extension and no defaultExtension configured for view template: ' + filename));
    }

    engine = this._engines[extension];
    if (!engine) {
        return callback(Boom.badImplementation('No view engine found for file: ' + filename));
    }

    var settings = Hoek.applyToDefaults(engine.config, options);

    this._path(filename + (fileExtension ? '' : engine.suffix), settings, false, function (err, templatePath) {

        if (err) {
            return callback(err);
        }

        self._compile(templatePath, engine, settings, function (err, compiled) {

            if (err) {
                return callback(err);
            }

            // No layout

            if (!settings.layout) {
                compiled(context, settings.runtimeOptions, function (err, rendered) {

                    if (err) {
                        return callback(Boom.badImplementation(err.message, err));
                    }

                    return callback(null, rendered, settings);
                });

                return;
            }

            // With layout

            if (context.hasOwnProperty(settings.layoutKeyword)) {
                return callback(Boom.badImplementation('settings.layoutKeyword conflict', { context: context, keyword: settings.layoutKeyword }));
            }

            self._path((settings.layout === true ? 'layout' : settings.layout) + engine.suffix, settings, true, function (err, layoutPath) {

                if (err) {
                    return callback(err);
                }

                self._compile(layoutPath, engine, settings, function (err, layout) {

                    if (err) {
                        return callback(err);
                    }

                    compiled(context, settings.runtimeOptions, function (err, rendered) {

                        if (err) {
                            return callback(Boom.badImplementation(err.message, err));
                        }

                        context[settings.layoutKeyword] = rendered;
                        layout(context, settings.runtimeOptions, function (err, rendered) {

                            delete context[settings.layoutKeyword];

                            if (err) {
                                return callback(Boom.badImplementation(err.message, err));
                            }

                            return callback(null, rendered, settings);
                        });
                    });
                });
            });
        });
    });
};
 handleEnqueueError : function(err) {
   this.getReply()(Boom.badImplementation(err));
 },
Example #22
0
    function () {

        return next(Boom.badImplementation('View file not found: ' + template));
    });
Example #23
0
 Item.find({ tags: request.params.tag }).sort('-created').exec(function(err, items) {
   if (!err) {
     return reply(items);
   }
   return reply(Boom.badImplementation(err)); // 500 error
 });
Example #24
0
 .catch((err) => {
   console.log('err', err);
   reply(Boom.badImplementation());
 });
Example #25
0
 Item.find({status:'available'}, function (err, items) {
   if (!err) {
     return reply(items);
   }
   return reply(Boom.badImplementation(err)); // 500 error
 });
Example #26
0
    var handler = function (request, reply) {

        var paths = normalized;
        if (typeof settings.path === 'function') {
            var result = settings.path.call(null, request);
            if (result instanceof Error) {
                return reply(result);
            }

            if (Array.isArray(result)) {
                paths = normalize(result);
            }
            else if (typeof result === 'string') {
                paths = normalize([result]);
            }
            else {
                return reply(Boom.badImplementation('Invalid path function'));
            }
        }

        // Append parameter

        var selection = null;
        var lastParam = request._paramsArray[request._paramsArray.length - 1];
        if (lastParam) {
            if (lastParam.indexOf('..') !== -1) {
                return reply(Boom.forbidden());
            }

            selection = lastParam;
        }

        if (selection &&
            !settings.showHidden &&
            internals.isFileHidden(selection)) {

            return reply(Boom.notFound());
        }

        // Generate response

        var resource = request.path;
        var hasTrailingSlash = (resource[resource.length - 1] === '/');

        Items.serial(paths, function (path, next) {

            path = Path.join(path, selection || '');

            File.load(path, request, { lookupCompressed: settings.lookupCompressed }, function (response) {

                // File loaded successfully

                if (!response.isBoom) {
                    return reply(response);
                }

                // Not found

                var err = response;
                if (err.output.statusCode === 404) {
                    if (!settings.defaultExtension) {
                        return next();
                    }

                    if (hasTrailingSlash) {
                        path = path.slice(0, -1);
                    }

                    return File.load(path + '.' + settings.defaultExtension, request, { lookupCompressed: settings.lookupCompressed }, function (extResponse) {

                        if (!extResponse.isBoom) {
                            return reply(extResponse);
                        }

                        return next();
                    });
                }

                // Directory

                var index = (settings.index !== false);                         // Defaults to true
                if (!index &&
                    !settings.listing) {

                    return reply(Boom.forbidden());
                }

                if (settings.redirectToSlash !== false &&                       // Defaults to true
                    !request.server.settings.router.stripTrailingSlash &&
                    !hasTrailingSlash) {

                    return reply.redirect(resource + '/');
                }

                if (!index) {
                    return internals.generateListing(path, resource, selection, hasTrailingSlash, settings, request, reply);
                }

                var indexFile = Path.join(path, 'index.html');
                File.load(indexFile, request, { lookupCompressed: settings.lookupCompressed }, function (indexResponse) {

                    // File loaded successfully

                    if (!indexResponse.isBoom) {
                        return reply(indexResponse);
                    }

                    // Directory

                    var err = indexResponse;
                    if (err.output.statusCode !== 404) {
                        return reply(Boom.badImplementation('index.html is a directory'));
                    }

                    // Not found

                    if (!settings.listing) {
                        return reply(Boom.forbidden());
                    }

                    return internals.generateListing(path, resource, selection, hasTrailingSlash, settings, request, reply);
                });
            });
        },
        function (/* err */) {

            return reply(Boom.notFound());
        });
    };
Example #27
0
 Item.findOne({ _id: request.params.itemId }, function (err, item) {
   if (!err) {
     return reply(item);
   }
   return reply(Boom.badImplementation(err)); // 500 error
 });
Example #28
0
function loginThroughOauth(request, reply, party, config) {
  if( request.query.error && request.query.error === 'access_denied'){
    return reply.redirect('/#login?error='+request.query.error );
  }
  /*jshint camelcase: false */
  var linkedIn = {
    oauth: {
      client_id: config.IN_CLIENT_ID,
      client_secret: config.IN_CLIENT_SECRET,
      redirect_uri: config.IN_CALLBACK_URL,
      grant_type: 'authorization_code',
      code: request.query.code
    },
    url: 'https://www.linkedin.com/uas/oauth2/accessToken'
  };
  var facebook = {
    oauth: {
      client_id: config.FB_CLIENT_ID,
      client_secret: config.FB_CLIENT_SECRET,
      redirect_uri: config.FB_CALLBACK_URL,
      grant_type: 'authorization_code',
      code: request.query.code
    },
    url: 'https://graph.facebook.com/v2.3/oauth/access_token?',
    graph: 'https://graph.facebook.com/v2.3/me?scope=email'
  };
  switch( party ) {
    case 'facebook':
      http.get( {
        url: facebook.url,
        qs: facebook.oauth
      }, function(err, httpResponse, body){
        var firstBody = body;
        http.get({
          url: 'https://graph.facebook.com/v2.3/me?scope=email',
          headers: {
            Authorization: 'Bearer ' + JSON.parse(firstBody).access_token
          }
        }, function(err, httpResponse, body) {
          try {
            findUserForOauth( JSON.parse(body).email, JSON.parse(body).first_name, JSON.parse(body).last_name, reply );
          } catch(e){
            reply('FAILED');
          }
        });
      });
      break;
    case 'linkedin':
      http.post( {
        url: linkedIn.url,
        form: linkedIn.oauth
      }, function(err, httpResponse, body){
        var firstBody = body;
        http.get({
          url: 'https://api.linkedin.com/v1/people/~:(first-name,last-name,headline,location,industry,picture-url,email-address)?format=json',
          headers: {
            Authorization: 'Bearer ' + JSON.parse(firstBody).access_token
          }
        }, function(err, httpResponse, body) {
          try {
            findUserForOauth( JSON.parse(body).emailAddress, JSON.parse(body).firstName, JSON.parse(body).lastName, reply);
          } catch(e){
            reply('FAILED');
          }
        });
      });
      break;
    default:
      return reply( Boom.badImplementation() );
  }
}
Example #29
0
 .catch(err => {
     console.log(err);
     return reply(Boom.badImplementation('No idea what happened'));
 });
 function insertCb(err, result) {
   if(err) return next(Boom.badImplementation(err.message));
   return next(null, result);
 }