Example #1
0
export function esNodesRoute(server) {
  server.route({
    method: 'POST',
    path: '/api/monitoring/v1/clusters/{clusterUuid}/elasticsearch/nodes',
    config: {
      validate: {
        params: Joi.object({
          clusterUuid: Joi.string().required()
        }),
        payload: Joi.object({
          ccs: Joi.string().optional(),
          timeRange: Joi.object({
            min: Joi.date().required(),
            max: Joi.date().required()
          }).required()
        })
      }
    },
    async handler(req, reply) {
      const config = server.config();
      const ccs = req.payload.ccs;
      const clusterUuid = req.params.clusterUuid;
      const esIndexPattern = prefixIndexPattern(config, 'xpack.monitoring.elasticsearch.index_pattern', ccs);

      try {
        const clusterStats = await getClusterStats(req, esIndexPattern, clusterUuid);
        const shardStats = await getShardStats(req, esIndexPattern, clusterStats, { includeNodes: true });
        const clusterStatus = getClusterStatus(clusterStats, shardStats);
        const nodes = await getNodes(req, esIndexPattern, clusterStats, shardStats);

        reply({ clusterStatus, nodes, });
      } catch(err) {
        reply(handleError(err, req));
      }
    }
  });

}
Example #2
0
router.post('/', (req, res) => {
  const schema = {
    title: joi.string().required(),
    url: joi.string().uri().required(),
    description: joi.string(),
    isProtected: joi.boolean(),
    datePublished: joi.date().min('1995-01-01'),
    dateCreated: joi.date(),
    stars: joi.number().integer().min(1)
    .max(5),
    tags: joi.array().items(joi.string()).min(1),
  };

  const results = joi.validate(req.body, schema);

  if (results.error) {
    console.log('results.error: ', results.error);
    return res.status(400).send({ messages: results.error.details.map(d => d.message) });
  }

  Bookmark.create(results.value, (err, bookmark) => {
    res.send({ bookmark });
  });
});
Example #3
0
    it('should handle date hash key', function () {
      var config = {
        hashKey: 'timestamp',
        schema : {
          timestamp : Joi.date()
        }
      };

      var s = new Schema(config);

      var d = new Date();
      var keys = serializer.buildKey(d, null, s);

      keys.should.eql({timestamp: d.toISOString()});
    });
Example #4
0
module.exports = ({ log, jwt }) => ({
  indexGet: {
    config: {
      validate: {},
      response: {
        schema: Joi.object().keys({ status: Joi.boolean(), time: Joi.date().timestamp() }).label('Healthz Response')
      },
      description: 'Whether the server is up or not.',
    },
    handler: async function(req){
      log.info('Got request for healthz.');
      return { status: true, time: new Date().valueOf() };
    }
  },
});
Example #5
0
module.exports = function (app) {

  var handler = function (request, reply) {
    app.server.methods.getTeachers(function (err, teachers) {
      if (err) {
        reply(Boom.serverTimeout(err));
      }
      reply({
        result: teachers,
        meta: {
          timestamp: moment().format()
        }
      });
    });
  };

  return {
    method: 'GET',
    path: '/v1/teachers',
    config: {
      handler: handler,
      response: {
        schema: Joi.object({
          result: Joi.array().includes(
              Joi.object({
                id: Joi.number().integer().required(),
                name: Joi.string().required(),
                foreName: Joi.string().allow('').required(),
                longName: Joi.string().required(),
                active: Joi.boolean().required()
              }).options({className: 'Teacher'})
          ).required(),
          meta: Joi.object({
            timestamp: Joi.date().required()
          }).required().options({className: 'Meta'})
        }).options({className: 'TeachersResponse'})
      },
      tags: ['api'],
      description: 'Fetch all teachers',
      notes: [
        'Returns an array of all teachers',
        'Error status codes',
        '503, Service Unavailable'
      ]
    }
  }

}
Example #6
0
 app.put('/api/spending/:id', tokenAuth, (req, res) => {
   const b = Joi.boolean().falsy([0, '0']).truthy([1, '1'])
   let schema = Joi.object().keys({
     category: Joi.string().min(1).trim(),
     title: Joi.string().min(1).trim(),
     amount: Joi.number().integer(),
     booked: b,
     bookedAt: Joi.date(),
     saving: b,
     paidWith: Joi.string().min(1).trim() // FIXME: Implement
   })
   Promise
     .try(() => {
       let v = Joi.validate(req.body, schema)
       if (v.error) {
         throw new ValidationFailedError('Validation failed', req.body, v.error)
       }
       return spendingRepo.getById(req.params.id)
         .then(spending => {
           checkVersionImmutable(req.headers['if-match'], spending)
           return spending
         })
         .then(spending => Promise
           .join(
             checkingAccountUserRepo.findByCheckingAccountId(req.params.id).filter(checkingAccountUser => checkingAccountUser.user === req.user),
             userRepo.getById(req.user)
           )
           .spread((checkingAccountUser, user) => {
             if (!checkingAccountUser) {
               throw new AccessDeniedError(req.url, 'Not your checking account!')
             }
             let cmd = new UpdateSpendingCommand(
               spending,
               v.value.category,
               v.value.title,
               v.value.amount,
               v.value.booked,
               v.value.bookedAt ? new Date(v.value.bookedAt) : undefined,
               v.value.saving,
               user
             )
             emitter.emit(cmd)
           })
         )
     })
     .then(() => res.status(202).send())
     .catch(sendHttpProblem.bind(null, res))
 })
Example #7
0
module.exports = function (app) {

  var handler = function (request, reply) {
    app.untis.timegrid().then(function (timegrid) {
      reply({
        result: timegrid,
        meta: {
          timestamp: moment().format()
        }
      });
    }, function (err) {
      reply(Boom.serverTimeout(err));
    });
  };

  return {
    method: 'GET',
    path: '/v1/timegrid',
    config: {
      handler: handler,
      response: {
        schema: Joi.object({
          result: Joi.array().includes(
              Joi.object({
                day: Joi.number().integer().required().description('1 = sunday, 2 = monday, ..., 7 = saturday'),
                lessons: Joi.array().includes(Joi.object({
                  name: Joi.string().allow('').required(),
                  startTime: Joi.object({hour: Joi.number().required(), minutes: Joi.number().required()}).options({className: 'LessonTime'}).required(),
                  endTime: Joi.object({hour: Joi.number().required(), minutes: Joi.number().required()}).options({className: 'LessonTime'}).required()
                }).required().options({className: 'Unit'})).required()
              }).required().options({className: 'Timegrid'})
          ).required(),
          meta: Joi.object({
            timestamp: Joi.date().required()
          }).required().options({className: 'Meta'})
        }).options({className: 'TimegridResponse'})
      },
      tags: ['api'],
      description: 'Fetch all timegrid units',
      notes: [
        'Returns an array of all timegrid units',
        'Error status codes',
        '503, Service Unavailable'
      ]
    }
  }

}
    it('from body', () => {
      const validation = parameterValidation({
          'in': 'body',
          'type': Joi.date(),
          'name': 'createdDate',
          'required': true
        },
        req);

      expect(validation)
        .to.be.a('boolean');

      expect(validation)
        .to.be.true;

      expect(req.body.createdDate)
        .to.be.a('Date');
    });
Example #9
0
    it('should serialize date attribute', function () {
      var config = {
        hashKey: 'time',
        schema : {
          time : Joi.date(),
        }
      };

      var s = new Schema(config);

      var d = new Date();
      var item = serializer.serializeItem(s, {time: d});
      item.should.eql({time: d.toISOString()});

      var now = Date.now();
      var item2 = serializer.serializeItem(s, {time: now});
      item2.should.eql({time: new Date(now).toISOString()});
    });
Example #10
0
module.exports = (models) => {
  return {
    listByDateAndUser: {
      handler: function (request, reply) {
        var params = lodash.assign(request.query, {user_id: request.auth.credentials.user});
        reply(this.Change.getByDateAndUser(params));
      },
      auth: 'token',
      validate: {
        query: {
          limit: joi.number().integer().min(1),
          offset: joi.number().integer().min(0),
          when: joi.date().required()
        }
      }
    }
  };
};
Example #11
0
  before(done => {
    vogels.dynamoDriver(helper.realDynamoDB());

    tableName = helper.randomName('vogels-updateTable-Tweets');

    Tweet = vogels.define('vogels-update-table-test', {
      hashKey: 'UserId',
      rangeKey: 'TweetID',
      tableName: tableName,
      schema: {
        UserId: Joi.string(),
        TweetID: vogels.types.uuid(),
        content: Joi.string(),
        PublishedDateTime: Joi.date().default(Date.now, 'now')
      }
    });

    vogels.createTables(done);
  });
Example #12
0
    beforeEach(function () {

      var config = {
        hashKey: 'name',
        rangeKey: 'email',
        schema : {
          name : Joi.string(),
          email : Joi.string(),
          created : Joi.date(),
          scores : Schema.types.numberSet()
        },
        indexes : [{ hashKey : 'name', rangeKey : 'created', type : 'local', name : 'CreatedIndex'}]
      };

      schema = new Schema(config);
      table.schema = schema;

      scan = new Scan(table, serializer);
    });
Example #13
0
 return q.fcall(function() {
   j.assert(query, {
     link: j.string().required(),
     image: j.string().allow(''),
     published_at: j.date().allow(''),
     author: j.string().allow(''),
     title: j.string().max(100).required(),
     description: j.string().max(1000).required(),
     article: j.string().max(50000).required()
   });
   return {
     link: query.link,
     image: query.image,
     title: query.title,
     description: query.description,
     article: query.article,
     published_at: query.published_at,
     author: query.author
   }
 }).then(function (result) {
Example #14
0
exports.register = function(server, options, next){
  server.route({
    method: 'PUT',
    path: '/profile',
    config: {
      description: 'Update user profile',
      validate: {
        payload: {
          email: Joi.string().email().required(),
          avatar: Joi.string().uri().required(),
          age: Joi.number().min(13).max(59).required(),
          address: Joi.string(),
          photo: Joi.string(),
          gender: Joi.string().required(),
          birthday: Joi.date().iso().required()
        }
      },
      handler: function(request, reply){
        if(request.auth.credentials._id){
          User.findByIdAndUpdate(request.auth.credentials._id, request.payload, saveCallback);
        }else{
          var user = new User(request.payload);
          user.uid = request.auth.credentials.uid;
          user.save(saveCallback);
        }

        function saveCallback(err, user){
          if(err){
            return reply(JSON.stringify(err)).code(400);
          }else{
            return reply(user);
          }
        }
      }
    }
  });

  return next();
};
module.exports = function (server, options, next) {

  server.dependency('isOpen')
  server.route({
    method: 'get',
    path: '/{time}',
    config: {
        validate: {
        params: {
          time: Joi.date()
        }
      },
      handler: (request, reply) => {
        request.seneca.act({ role: 'isOpen', time: request.params.time}, (err, result) => {
          reply(result.isOpen)
        })
      }
    }
  })

  next()
}
Example #16
0
  default: function renderHomePage(req,res){

    var schema = Joi.object().keys({

      dateOffset: Joi.date().min('4/4/1975').max('12/31/2999').default(new Date())
      , weekNumberOffset: Joi.number().integer().min(-1000).max(1000).default(0)
      , iterationOffset: Joi.number().integer().min(-1000).max(1000).default(0)
      , milestoneOffset: Joi.number().integer().min(-1000).max(1000).default(0)

    })
    Joi.validate({
      dateOffset: req.query.dateOffset
      , weekNumberOffset: req.query.weekNumberOffset
      , iterationOffset: req.query.iterationOffset
      , milestoneOffset: req.query.milestoneOffset
    }, schema, function (err, value) {
      if(err){
        sails.log(__filename,err)
        return(err)
      }

      sails.log(__filename,'date',value.dateOffset)

      value['schedule'] = createSchedule([m1,m2,m3,postThreshold], value.dateOffset)


      var lastWeek = new Date(value.dateOffset)
      lastWeek.setDate(lastWeek.getDate() - 7)
      value['lastWeek'] = lastWeek

      var nextWeek = new Date(value.dateOffset)
      nextWeek.setDate(nextWeek.getDate() + 7)
      value['nextWeek'] = nextWeek

      console.log(__filename, 'dates',value.dateOffset, value.lastWeek, value.nextWeek)
      res.view(value)
    });

  }
Example #17
0
  it('should add global secondary index', (done) => {
    Tweet = dynogels.define('dynogels-update-table-test', {
      hashKey: 'UserId',
      rangeKey: 'TweetID',
      tableName: tableName,
      schema: {
        UserId: Joi.string(),
        TweetID: dynogels.types.uuid(),
        content: Joi.string(),
        PublishedDateTime: Joi.date().default(Date.now, 'now')
      },
      indexes: [
        { hashKey: 'UserId', rangeKey: 'PublishedDateTime', type: 'global', name: 'PublishedDateTimeIndex' }
      ]
    });

    Tweet.updateTable((err) => {
      expect(err).to.not.exist;

      Tweet.describeTable((err, data) => {
        expect(err).to.not.exist;

        const globalIndexes = _.get(data, 'Table.GlobalSecondaryIndexes');
        expect(globalIndexes).to.have.length(1);

        const idx = _.first(globalIndexes);
        expect(idx.IndexName).to.eql('PublishedDateTimeIndex');
        expect(idx.KeySchema).to.eql([
          { AttributeName: 'UserId', KeyType: 'HASH' },
          { AttributeName: 'PublishedDateTime', KeyType: 'RANGE' }
        ]);
        expect(idx.Projection).to.eql({ ProjectionType: 'ALL' });

        return done();
      });
    });
  });
Example #18
0
exports.register = function (server, options, next) {

    server.route({
        config: {
            validate: {
                payload: {
                    code: Joi.string().required(),
                    lat: Joi.number().required(),
                    lng: Joi.number().required(),
                    alt: Joi.number().required(),
                    timestamp: Joi.date().required()
                }
            }
        },
        method: 'POST',
        path: '/api',
        handler: function (request, reply) {

            server.methods.database.addPing(request.payload, reply);
        }
    });

    next();
};
Example #19
0
  beforeEach(function () {
    serializer = helper.mockSerializer(),

    table = helper.mockTable();
    table.tableName = function () {
      return 'accounts';
    };

    table.docClient = helper.mockDocClient();

    var config = {
      hashKey: 'name',
      rangeKey: 'email',
      schema : {
        name : Joi.string(),
        email : Joi.string(),
        created : Joi.date()
      },
      indexes : [{ hashKey : 'name', rangeKey : 'created', type : 'local', name : 'CreatedIndex'}]
    };

    schema = new Schema(config);
    table.schema = schema;
  });
Example #20
0
import Joi from 'joi';
import user from './user.schema';

const keys = {
  user : Joi.alternatives().required().try([Joi.objectId(), user]),
  expiry : Joi.date().required()
};

const schema = Joi.object().keys(keys);

export default schema;

export {
  keys
};
Example #21
0
    config: {
        handler: handler,
        validate: {
            query: {
                param1: Joi.binary().min(42).max(128).length(64).encoding('base64')
            }
        }
    }
}, {
    method: 'GET',
    path: '/withdate',
    config: {
        handler: handler,
        validate: {
            query: {
                param1: Joi.date().min('1-1-1974').max('12-31-2020')
            }
        }
    }
}, {
    method: 'GET',
    path: '/withpeersconditions',
    config: {
        handler: handler,
        validate: {
            query: {
                param1: Joi.object()
                    .and('a', 'b', 'c')
                    .or('a', 'b', 'c')
                    .xor('a', 'b', 'c')
                    .with('a', ['b', 'c'])
Example #22
0
var utils = require('../../../../utils.js');
var is = require('joi');

module.exports = is.object({
  _id: is.string().regex(/^order_[0-9]+$/),
  doc_type: 'order',
  order_id: 1,
  user_id: is.number(),
  order_date: is.date(),
  order_status: [ 'Pending', 'Processing', 'Cancelled', 'Shipped' ],
  billing_name: is.string(),
  billing_phone: utils.phone,
  billing_email: is.string().email(),
  billing_address_1: is.string(),
  billing_address_2: [ is.string(), null ],
  billing_locality: is.string(),
  billing_region: is.string(),
  billing_postal_code: is.string(),
  billing_country: 'US',
  shipping_name: is.string(),
  shipping_address_1: is.string(),
  shipping_address_2: [ is.string(), null ],
  shipping_locality: is.string(),
  shipping_region: is.string().uppercase().length(2),
  shipping_postal_code: utils.postal_code,
  shipping_country: 'US',
  shipping_method: is.string(),
  shipping_total: is.number().precision(2),
  tax: is.number().precision(2).min(2.00).max(10.99),
  line_items: is.array()
    .items({
Example #23
0
export function esIndexRoute(server) {

  server.route({
    method: 'POST',
    path: '/api/monitoring/v1/clusters/{clusterUuid}/elasticsearch/indices/{id}',
    config: {
      validate: {
        params: Joi.object({
          clusterUuid: Joi.string().required(),
          id: Joi.string().required()
        }),
        payload: Joi.object({
          ccs: Joi.string().optional(),
          timeRange: Joi.object({
            min: Joi.date().required(),
            max: Joi.date().required()
          }).required(),
          is_advanced: Joi.boolean().required()
        })
      }
    },
    handler: async (req, reply) => {
      try {
        const config = server.config();
        const ccs = req.payload.ccs;
        const clusterUuid = req.params.clusterUuid;
        const indexUuid = req.params.id;
        const start = req.payload.timeRange.min;
        const end = req.payload.timeRange.max;
        const esIndexPattern = prefixIndexPattern(config, 'xpack.monitoring.elasticsearch.index_pattern', ccs);
        const isAdvanced = req.payload.is_advanced;
        const metricSet = isAdvanced ? metricSetAdvanced : metricSetOverview;

        const cluster = await getClusterStats(req, esIndexPattern, clusterUuid);
        const showSystemIndices = true; // hardcode to true, because this could be a system index

        const shardStats = await getShardStats(req, esIndexPattern, cluster, { includeNodes: true, includeIndices: true });
        const indexSummary = await getIndexSummary(req, esIndexPattern, shardStats, { clusterUuid, indexUuid, start, end });
        const metrics = await getMetrics(req, esIndexPattern, metricSet, [{ term: { 'index_stats.index': indexUuid } }]);

        let shardAllocation;
        if (!isAdvanced) {
          // TODO: Why so many fields needed for a single component (shard legend)?
          const shardFilter = { term: { 'shard.index': indexUuid } };
          const stateUuid = get(cluster, 'cluster_state.state_uuid');
          const allocationOptions = {
            nodeResolver: config.get('xpack.monitoring.node_resolver'),
            shardFilter,
            stateUuid,
            showSystemIndices,
          };
          const shards = await getShardAllocation(req, esIndexPattern, allocationOptions);

          shardAllocation = {
            shards,
            shardStats: { nodes: shardStats.nodes },
            nodes: shardStats.nodes, // for identifying nodes that shard relocates to
            stateUuid, // for debugging/troubleshooting
          };
        }

        reply({
          indexSummary,
          metrics,
          ...shardAllocation,
        });

      } catch (err) {
        reply(handleError(err, req));
      }
    }
  });

}
Example #24
0

Admin.schema = Joi.object().keys({
    _id: Joi.object(),
    user: Joi.object().keys({
        id: Joi.string().required(),
        name: Joi.string().lowercase().required()
    }),
    groups: Joi.object().description('{ groupId: name, ... }'),
    permissions: Joi.object().description('{ permission: boolean, ... }'),
    name: Joi.object().keys({
        first: Joi.string().required(),
        middle: Joi.string().allow(''),
        last: Joi.string().required()
    }),
    timeCreated: Joi.date()
});


Admin.indexes = [
    { key: { 'user.id': 1 } },
    { key: { 'user.name': 1 } }
];


Admin.create = function (name, callback) {

    const nameParts = name.trim().split(/\s/);

    const document = {
        name: {
Example #25
0
module.exports = (gatepost) => {

  const Post = new gatepost.Model({
    id: {
      validate: joi.number().integer(),
      primary: true
    },
    author: {
      validate: joi.string().max(50)
    },
    body: {
      validate: joi.string()
    },
    parent_id: {
      validate: joi.number().integer()
    },
    thread_id: {
      validate: joi.number().integer()
    },
    path: {
      processIn: function (value) {
        if (!value) {
          return [];
        }
        return value.split('.');
      },
      processOut: function (value) {
        if (!value) {
          return '';
        }
        return value.join('.');
      },
      //validate: joi.string().max(255)
    },
    created: {
      validate: joi.date()
    },
    updated: {
      validate: joi.date()
    }
  }, {
    name: 'post',
    cach: true
  });

  const PostPage = new gatepost.Model({
    count: {type: 'integer'},
    total: {type: 'integer'},
    results: {collection: Post}
  });

  Post.registerFactorySQL({
    name: "get",
    sql: (args) => SQL`SELECT posts.id, posts.author, posts.body, posts.parent_id, posts.thread_id, posts.path, posts.created, posts.updated FROM posts
  JOIN threads ON posts.thread_id=threads.id
  JOIN forums ON threads.forum_id=forums.id
  JOIN forums_access ON forums_access.forum_id=forums.id
  WHERE posts.id=${args.post_id} AND ((forums_access.user_id=${args.user_id} AND forums_access.read=True) OR forums.owner=${args.user_id})`,
    oneResult: true
  });

  Post.registerFactorySQL({
    name: "deconste",
    sql: (args) => SQL`DELETE FROM posts WHERE id=${args.id}`,
    oneResult: true
  });

  Post.fromSQL({
    name: 'insert',
    instance: true,
    sql: (args, model) => SQL`SELECT * FROM create_post(${model.toJSON()}, ${args.user})`,
    oneResult: true,
    require: true
  });

  Post.fromSQL({
    name: 'update',
    instance: true,
    sql: (args, model) => SQL`SELECT update_post(${model.toJSON()}, ${args.user}) AS id`,
    oneResult: true,
    require: true
  });


  PostPage.fromSQL({
    name: "all",
    sql: (args) => SQL`SELECT (SELECT n_live_tup FROM pg_stat_user_tables WHERE relname='posts') AS total,
      json_agg(row_to_json(post_rows)) as results,
      count(post_rows.*)::INTEGER as count
      FROM (SELECT id, author, body, parent_id, thread_id, path, created, updated
      FROM posts
      JOIN threads ON posts.thread_id=threads.id
      JOIN forums ON threads.forum_id=forums.id
      JOIN forums_access ON forums_access.forum_id=forums.id
      WHERE (forums_access.user_id=${args.user_id} AND forums_access.read=True) OR forums.owner=${args.user_id}
      ORDER BY posts.id LIMIT ${args.limit} OFFSET ${args.offset}) post_rows`,
    defaults: {
      limit: 20,
      offset: 0
    },
    oneResult: true
  });

  PostPage.registerFactorySQL({
    name: 'allByThread',
    sql: (args) => SQL`SELECT (SELECT count(id)::INTEGER FROM posts WHERE thread_id=${args.thread_id}) AS total,
  json_agg(row_to_json(post_rows)) as results,
  count(post_rows.*)::INTEGER as count
  FROM (WITH RECURSIVE included_posts(id, author, body, parent_id, thread_id, path, created, updated) AS (
    SELECT id, author, body, parent_id, thread_id, path, created, updated FROM posts WHERE parent_id IS NULL AND thread_id=${args.thread_id}
  UNION ALL
    SELECT p.id, p.author, p.body, p.parent_id, p.thread_id, p.path, p.created, p.updated FROM included_posts inc_p, posts p WHERE p.parent_id=inc_p.id
  )
  SELECT included_posts.* FROM included_posts
  JOIN threads ON included_posts.thread_id=threads.id
  JOIN forums ON threads.forum_id=forums.id
  JOIN forums_access ON forums_access.forum_id=forums.id
  WHERE (forums_access.user_id=${args.user_id} AND forums_access.read=True) OR forums.owner=${args.user_id}
  ORDER BY included_posts.path LIMIT ${args.limit} OFFSET ${args.offset}) post_rows`,
    defaults: {
      limit: 20,
      offset: 0
    },
    oneResult: true
  });

  Post.all = PostPage.all;
  Post.allByThread = PostPage.allByThread;

  return Post;
};
Example #26
0
var uuid = require("uuid");
var nodemailer = require("nodemailer");
var faker = require("faker");
var profileModel = require(__dirname + "/../../api/profiles/index").model();
var inMemoryKeys = {};

var schema = {
  username : Joi.string().email().required(),
  password : Joi.string().required(),
}

var hawkTokenSchema = {
  userId : Joi.string().required(),
  tokenId : Joi.string().required(),
  key : Joi.string().required(),
  date : Joi.date().required()
}

global.inMemoryTokens = {
  tokens: {},
  get: function(id) {
    return this.tokens[id];
  },
  set: function(id, val) {
    this.tokens[id] = val;
  },
  del: function(id) {
    delete this.tokens[id];
  },
  exists: function(id) {
    var r = typeof this.tokens[id] !== 'undefined';
Example #27
0
        var userId = req.query.userId;
        var date = req.query.date;
        var toDate = req.query.toDate;
        var platform = req.query.platform;
        var query = req.query.query;
        var userType = req.query.userType;
        reply.co(AppsHandler.getApps(date, toDate, platform, appStatus, page, pageSize, userId, userType, query));
    },
    config: {
        validate: {
            query: {
                platform: Joi.array().items(Joi.string()).valid(PLATFORMS).required(),
                page: Joi.number().integer().min(1).optional(),
                pageSize: Joi.number().integer().min(1).optional(),
                userId: Joi.string().optional(),
                date: Joi.date().optional(),
                status: Joi.string().valid(APP_STATUSES).optional(),
                userType: Joi.string().valid(_.values(USER_TYPES)).optional(),
                toDate: Joi.date().optional(),
                query: Joi.string().optional()
            }
        },
        auth: false,
        description: 'Get available apps by date. UserId is optional if you want to know if the user has voted for each app.',
        tags: ['api']
    }
}, {
    method: "GET",
    path: "/apps/trending",
    handler: function handler(req, reply) {
        var page = req.query.page === undefined ? 0 : req.query.page;
Example #28
0
exports.register = function (server, options, next) {
  options = _.extend({ basePath: '/api/2.0' }, options);
  var handlers = require('./handlers.js')(server, 'cd-dojos');

  server.route([{
    method: 'GET',
    path: options.basePath + '/dojos/config',
    handler: handlers.actHandler('get_dojo_config'),
    config: {
      description: 'Config endpoint',
      notes: 'Returns the dojo configuration',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/search-bounding-box',
    handler: handlers.actHandler('search_bounding_box'),
    config: {
      description: 'Search dojos',
      notes: 'Search dojos located in a bounding box area',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request' },
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          lat: joiValidator.latitude().required(),
          lon: joiValidator.longitude().required(),
          radius: Joi.number().min(0).required(),
          search: Joi.string()
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/find',
    handler: handlers.actHandler('find'),
    config: {
      description: 'Find',
      notes: 'Find',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request' },
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          dojoLeadId: joiValidator.guid(),
          urlSlug: Joi.string()
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/search',
    handler: handlers.actHandler('search'),
    config: {
      description: 'Search dojos',
      notes: 'Search dojos',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request' },
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          name: Joi.string().optional(),
          verified: Joi.number().integer(),
          email: Joi.string().optional(),
          creatorEmail: Joi.string().optional(),
          stage: Joi.number().integer().optional(),
          alpha2: joiValidator.alpha2().optional().description('two capital letters representing the country'),
          limit$: Joi.number().integer().min(0).optional(),
          skip$: Joi.number().integer().min(0).optional(),
          sort$: Joi.object().keys({
            created: Joi.number().valid(-1).valid(1).optional()
          })
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/manage-dojos',
    handler: handlers.actHandlerNeedsCdfAdmin('search'),
    config: {
      description: 'Search dojos for manage dojos page',
      notes: 'Only accessible by cdf-admins',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request' },
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          name: Joi.string().optional(),
          verified: Joi.number().integer(),
          email: Joi.string().optional(),
          creatorEmail: Joi.string().optional(),
          stage: Joi.number().integer().optional(),
          alpha2: joiValidator.alpha2().optional().description('two capital letters representing the country'),
          limit$: Joi.number().integer().min(0).optional(),
          skip$: Joi.number().integer().min(0).optional(),
          sort$: Joi.object().keys({
            created: Joi.number().valid(-1).valid(1).optional(),
            name: Joi.number().valid(-1).valid(1).optional(),
            stage: Joi.number().valid(-1).valid(1).optional(),
            alpha2: Joi.number().valid(-1).valid(1).optional(),
            email: Joi.number().valid(-1).valid(1).optional()
          })
        }})
      }
    }
  }, {
    method: 'POST',
      path: options.basePath + '/dojos/create',
      handler: handlers.actHandlerNeedsUser('create'),
      config: {
        description: 'Create',
        notes: 'Create',
        tags: ['api'],
        plugins: {
          'hapi-swagger': {
            responseMessages: [
              { code: 400, message: 'Bad Request'},
              { code: 200, message: 'OK'}]
          }
        },
        validate: {
          payload: Joi.object({ dojo: {
            stage: Joi.number().integer().required(),
            notes: Joi.string().required(),
            name: Joi.string().required(),
            email: joiValidator.mail(),
            time: Joi.string(),
            country: joiValidator.country(),
            placeName: Joi.string().required(),
            county: Joi.object().allow(null),
            state: Joi.object().allow(null),
            city: Joi.object().allow(null),
            place: joiValidator.place(),
            countryName: Joi.string().required(),
            countryNumber: Joi.number().integer(),
            continent: joiValidator.continent(),
            alpha2: joiValidator.alpha2().required(),
            alpha3: joiValidator.alpha3().required(),
            address1: Joi.string().required(),
            coordinates: Joi.string().required(),
            needMentors: Joi.number().integer(),
            taoVerified: Joi.number().integer(),
            'private': Joi.number().valid(0).valid(1),
            googleGroup: joiValidator.uri(),
            website: joiValidator.uri(),
            twitter: joiValidator.twitter(),
            supporterImage: joiValidator.uri(),
            mailingList: Joi.number().integer(),
            dojoLeadId: joiValidator.guid().required(),
            emailSubject: Joi.string().required()
          }})
        }
      }
    }, {
    method: 'PUT',
    path: options.basePath + '/dojos/{id}',
    handler: handlers.actHandlerNeedsUser('update', 'id'),
    config: {
      description: 'Update',
      notes: 'Update',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        },
        payload: Joi.object({ dojo: {
          entity$: Joi.string(),
          id: joiValidator.guid(),
          mysqlDojoId: Joi.any(),
          dojoLeadId: joiValidator.guid(),
          name: Joi.string(),
          creator: joiValidator.guid(),
          created: Joi.date(),
          verifiedAt: Joi.alternatives().try(Joi.date(), Joi.string().valid(null)),
          verifiedBy: Joi.alternatives().try(joiValidator.guid(), Joi.string().valid(null)),
          verified: Joi.number().valid(0).valid(1),
          needMentors: Joi.number().valid(0).valid(1),
          taoVerified: Joi.number().valid(0).valid(1),
          stage: Joi.number().integer(),
          mailingList: Joi.number().integer(),
          time: Joi.string().allow("").allow(null),
          country: joiValidator.country(),
          county: Joi.object().allow(null),
          state: Joi.object().allow(null),
          city: Joi.object().allow(null),
          place: joiValidator.place(),
          coordinates: Joi.string(),
          geoPoint: Joi.object().keys({
            lat: joiValidator.latitude(),
            lon: joiValidator.longitude()
          }),
          notes: Joi.string().allow("").allow(null),
          email: Joi.alternatives().try(joiValidator.mail(), Joi.string().valid(null).valid("")),
          googleGroup: Joi.alternatives().try(joiValidator.uri(), Joi.string().valid(null).valid("")),
          website: Joi.alternatives().try(joiValidator.uri(), Joi.string().valid(null).valid("")),
          twitter: Joi.alternatives().try(joiValidator.twitter(), Joi.string().valid(null).valid("")),
          ebId: Joi.any(),
          supporterImage: Joi.alternatives().try(joiValidator.uri(), Joi.string().valid(null), Joi.string().valid("")),
          deleted: Joi.number().valid(0).valid(1),
          deletedBy: Joi.any(),
          deletedAt: Joi.any(),
          'private': Joi.number().valid(0).valid(1),
          urlSlug: Joi.string(),
          continent: joiValidator.continent(),
          alpha2: joiValidator.alpha2(),
          alpha3: joiValidator.alpha3(),
          address1: Joi.string(),
          address2: Joi.any(),
          countryNumber: Joi.number().integer(),
          countryName: Joi.string(),
          admin1Code: Joi.any(),
          admin1Name: Joi.any(),
          admin2Code: Joi.any(),
          admin2Name: Joi.any(),
          admin3Code: Joi.any(),
          admin3Name: Joi.any(),
          admin4Code: Joi.any(),
          admin4Name: Joi.any(),
          placeGeonameId: Joi.any(),
          placeName: Joi.string(),
          userInvites: Joi.alternatives().try(Joi.array().items(Joi.object().keys({
            id: Joi.string(),
            email: joiValidator.mail(),
            userType: Joi.string(),
            timestamp: Joi.date()
          })), Joi.string().valid(null)),
          creatorEmail: joiValidator.mail(),
          emailSubject: Joi.string(),
          editDojoFlag: Joi.boolean()
        }})
      }
    }
  }, {
    method: 'DELETE',
    path: options.basePath + '/dojos/{id}',
    handler: handlers.actHandlerNeedsUser('delete', 'id'),
    config: {
      description: 'Delete dojo',
      notes: 'Delete a dojo providing the dojo id',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/delete/{id}',
    handler: handlers.actHandlerNeedsUser('delete', 'id'),
    config: {
      description: 'Delete dojo',
      notes: 'Delete a dojo providing the dojo id',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/by-country',
    handler: handlers.actHandler('dojos_by_country'),
    config: {
      description: 'ByCountry',
      notes: 'ByCountry',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          verified: Joi.number().valid(0).valid(1),
          deleted: Joi.number().valid(0).valid(1)
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos',
    handler: handlers.actHandler('list'),
    config: {
      description: 'List',
      notes: 'List',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.alternatives().try(Joi.any(), Joi.object({ query: {
          name: Joi.string(),
          verified: Joi.number().valid(0).valid(1),
          stage: Joi.number().integer(),
          deleted: Joi.number().valid(0).valid(1),
          alpha2:joiValidator.alpha2(),
          fields$: Joi.array()
        }}))
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/my-dojos',
    handler: handlers.actHandlerNeedsUser('my_dojos'),
    config: {
      description: 'MyDojos',
      notes: 'MyDojos',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ search: {
          sort: Joi.object().keys({
            created: Joi.number().valid(0).valid(1)
          }),
          from: Joi.number().integer().min(0),
          size: Joi.number().integer().min(0)
        }})
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/{id}',
    handler: handlers.actHandler('load', 'id'),
    config: {
      description: 'dojos',
      notes: 'dojos',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/bulk-update',
    handler: handlers.actHandlerNeedsUser('bulk_update'),
    config: {
      description: 'bulk',
      notes: 'bulk',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ dojos:
          Joi.array().items(Joi.object().keys({
            id: joiValidator.guid(),
            verified: Joi.number().valid(0).valid(1),
            dojoLeadId: joiValidator.guid()
          }))
        })
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/bulk-delete',
    handler: handlers.actHandlerNeedsUser('bulk_delete'),
    config: {
      description: 'bulk',
      notes: 'bulk',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ dojos:
          Joi.array().items(Joi.object().keys({
            id: joiValidator.guid(),
            creator: joiValidator.guid(),
            dojoLeadId: joiValidator.guid()
          }))
        })
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/stats',
    handler: handlers.actHandlerNeedsUser('get_stats'),
    config: {
      description: 'get stats',
      notes: 'get stats',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/save-dojo-lead',
    handler: handlers.actHandlerNeedsUser('save_dojo_lead'),
    config: {
      description: 'lead',
      notes: 'lead',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        payload: Joi.object({ dojoLead: {
          application: joiValidator.application(),
          userId: joiValidator.guid().required(),
          email: joiValidator.mail().required(),
          currentStep: Joi.number().integer(),
          migration: Joi.any(),
          completed: Joi.boolean()
        }})
      }
    }
  }, {
    method: 'PUT',
    path: options.basePath + '/dojos/update-dojo-lead/{id}',
    handler: handlers.actHandlerNeedsUser('update_dojo_lead', 'id'),
    config: {
      description: 'update lead',
      notes: 'update lead',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        },
        payload: Joi.object({ dojoLead: {
          entity$: Joi.string(),
          userId: joiValidator.guid().required(),
          email: joiValidator.mail().required(),
          application: joiValidator.application(),
          currentStep: Joi.number().integer(),
          id: joiValidator.guid().required(),
          completed: Joi.boolean(),
          deleted: Joi.number().valid(0).valid(1),
          deletedBy: Joi.any(),
          deletedAt: Joi.any(),
          converted: Joi.any(),
          migration: Joi.any()
        }})
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/user-dojo-lead/{id}',
    handler: handlers.actHandlerNeedsUser('load_user_dojo_lead', 'id'),
    config: {
      description: 'load lead',
      notes: 'load lead',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/dojo-lead/{id}',
    handler: handlers.actHandlerNeedsUser('load_dojo_lead', 'id'),
    config: {
      description: 'dojo lead',
      notes: 'dojo lead',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/setup-steps',
    handler: handlers.actHandlerNeedsUser('load_setup_dojo_steps'),
    config: {
      description: 'dojo steps',
      notes: 'dojo steps',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/users',
    handler: handlers.actHandler('load_usersdojos'),
    config: {
      description: 'dojo users',
      notes: 'dojo users',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          dojoId: Joi.alternatives().try(joiValidator.guid(), Joi.string().valid("")),
          userId: joiValidator.guid(),
          deleted: Joi.number().valid(0).valid(1),
          owner: Joi.number().valid(1).valid(0),
          limit$: Joi.number().integer().min(0).optional(),
          skip$: Joi.number().integer().min(0).optional()
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/search-dojo-leads',
    handler: handlers.actHandler('search_dojo_leads'),
    config: {
      description: 'dojo leads',
      notes: 'dojo leads',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          userId: joiValidator.guid()
        }})
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/uncompleted',
    handler: handlers.actHandler('uncompleted_dojos'),
    config: {
      description: 'uncompleted',
      notes: 'uncompleted',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/load-dojo-users',
    handler: handlers.actHandler('load_dojo_users'),
    config: {
      description: 'dojo users',
      notes: 'dojo users',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          dojoId: joiValidator.guid(),
          deleted: Joi.number().valid(0).valid(1),
          limit$: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string()),
          skip$: Joi.number().integer().min(0).optional(),
          sort$: Joi.object().keys({
            name: Joi.number().valid(-1).valid(1).optional(),
            email: Joi.number().valid(-1).valid(1).optional()
          })
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/generate-user-invite-token',
    handler: handlers.actHandler('generate_user_invite_token'),
    config: {
      description: 'user invite token',
      notes: 'user invite token',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        payload: Joi.object({
          email: joiValidator.mail().required(),
          emailSubject: Joi.string(),
          userType: Joi.string(),
          dojoId: joiValidator.guid().required()
        })
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/accept-user-invite',
    handler: handlers.actHandler('accept_user_invite'),
    config: {
      description: 'accept invite',
      notes: 'accept invite',
      tags: ['api']
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/request-user-invite',
    handler: handlers.actHandler('request_user_invite'),
    config: {
      description: 'request invite',
      notes: 'request invite',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        payload: Joi.object({ data: {
          user: joiValidator.user().required(),
          dojoId: joiValidator.guid().required(),
          userType: Joi.string(),
          emailSubject: Joi.string()
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/accept-user-request',
    handler: handlers.actHandler('accept_user_request'),
    config: {
      description: 'accept request',
      notes: 'accept request',
      tags: ['api']
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/dojos-for-user/{id}',
    handler: handlers.actHandler('dojos_for_user', 'id'),
    config: {
      description: 'dojos for user',
      notes: 'dojos for user',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          id: Joi.string().required()
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/save-usersdojos',
    handler: handlers.actHandler('save_usersdojos'),
    config: {
      description: 'save user dojos',
      notes: 'save user dojos',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        payload: Joi.object({ userDojo: {
          entity$: Joi.string(),
          id: joiValidator.guid(),
          mysqlUserId: Joi.any(),
          mysqlDojoId: Joi.any(),
          owner: Joi.number().valid(1).valid(0),
          userId: joiValidator.guid(),
          dojoId: joiValidator.guid(),
          userTypes: Joi.array(),
          userPermissions: Joi.alternatives().try(Joi.array(), Joi.string().valid(null)),
          backgroundChecked: Joi.boolean(),
          deleted: Joi.number().valid(0).valid(1),
          deletedBy: Joi.any(),
          deletedAt: Joi.any()
        }})
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/remove-usersdojos/{userId}/{dojoId}',
    handler: handlers.actHandlerNeedsUser('remove_usersdojos', ['userId', 'dojoId']),
    config: {
      description: 'remove user dojos',
      notes: 'remove user dojos',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        params: {
          userId: joiValidator.guid().required(),
          dojoId: joiValidator.guid().required()
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/user-permissions',
    handler: handlers.actHandler('get_user_permissions'),
    config: {
      description: 'user permissions',
      notes: 'user permissions',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/dojos/user-types',
    handler: handlers.actHandler('get_user_types'),
    config: {
      description: 'user types',
      notes: 'user types',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/update-founder',
    handler: handlers.actHandlerNeedsUser('update_founder'),
    config: {
      description: 'update founder',
      notes: 'update founder',
      tags: ['api']
    }
  }, {
    method: 'POST',
    path: options.basePath + '/dojos/search-nearest-dojos',
    handler: handlers.actHandler('search_nearest_dojos'),
    config: {
      description: 'search nearest dojo',
      notes: 'search nearest dojo',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request' },
            { code: 200, message: 'OK'}
          ]
        }
      },
      validate: {
        payload: Joi.object({ query: {
          lat: joiValidator.latitude().required(),
          lon: joiValidator.longitude().required()
        }})
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/countries',
    handler: handlers.actHandler('list_countries'),
    config: {
      cache: {
        expiresIn: cacheTimes.long
      },
      description: 'list countries',
      notes: 'list countries',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'POST',
    path: options.basePath + '/countries/places',
    handler: handlers.actHandler('list_places'),
    config: {
      description: 'list places',
      notes: 'list places',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 400, message: 'Bad Request'},
            { code: 200, message: 'OK'}]
        }
      },
      validate: {
        payload: Joi.object({ search: {
          countryCode: joiValidator.alpha2().required(),
          search: Joi.string().required()
        }})
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/countries/continents/lat-long',
    handler: handlers.actHandler('continents_lat_long'),
    config: {
      cache: {
        expiresIn: cacheTimes.long
      },
      description: 'continents lat long',
      notes: 'continents lat long',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/countries/lat-long',
    handler: handlers.actHandler('countries_lat_long'),
    config: {
      cache: {
        expiresIn: cacheTimes.long
      },
      description: 'countries lat long',
      notes: 'countries lat long',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/countries/continents/codes',
    handler: handlers.actHandler('continent_codes'),
    config: {
      cache: {
        expiresIn: cacheTimes.long
      },
      description: 'continent codes',
      notes: 'continent codes',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }, {
    method: 'GET',
    path: options.basePath + '/countries/continents',
    handler: handlers.actHandler('countries_continents'),
    config: {
      cache: {
        expiresIn: cacheTimes.long
      },
      description: 'countries continents',
      notes: 'countries continents',
      tags: ['api'],
      plugins: {
        'hapi-swagger': {
          responseMessages: [
            { code: 200, message: 'OK'}
          ]
        }
      }
    }
  }]);

  next();
};
Example #29
0
module.exports = function () {
  const joiValidator = {
    latitude() {
      return Joi.number().min(-90).max(90);
    },
    longitude() {
      return Joi.number().min(-180).max(180);
    },
    mail() {
      return Joi.string().email();
    },
    alpha2() {
      return Joi.string().length(2).regex(/[A-Z]{2}/);
    },
    alpha3() {
      return Joi.string().length(3).regex(/[A-Z]{3}/);
    },
    continent() {
      return Joi.string().length(2).regex(/[A-Z]{2}/);
    },
    twitter() {
      return Joi.string().regex(/^[a-z0-9_]{1,15}$/i).allow('').allow(null);
    },
    facebook() {
      return Joi.string().regex(/^[a-z0-9.]{1,}$/i).allow('').allow(null);
    },
    linkedin() {
      return Joi.string().regex(/^[a-z0-9-]{1,}$/i).allow('').allow(null);
    },
    uri() {
      return Joi.alternatives().try(Joi.string().uri(), Joi.string());
    },
    optionalUri() {
      return Joi.alternatives().try(joiValidator.uri(), Joi.string().empty(''), Joi.string().valid(null));
    },
    country() {
      return Joi.object().keys({
        countryName: Joi.string().required(),
        countryNumber: Joi.alternatives().try(Joi.string(), Joi.number()),
        continent: joiValidator.continent(),
        alpha2: joiValidator.alpha2(),
        alpha3: joiValidator.alpha3(),
      });
    },
    phone() {
      return Joi.string();
    },
    place() {
      return Joi.object().keys({
        nameWithHierarchy: Joi.string(),
        toponymName: Joi.string(),
      });
    },
    frequency() {
      return Joi.string().only(['1/w', '1/m', '2/m', 'other']);
    },
    day() {
      return Joi.number().only([1, 2, 3, 4, 5, 6, 7]);
    },
    champion(required) {
      const valid = {
        firstName: Joi.string(),
        lastName: Joi.string(),
        email: joiValidator.mail(),
        dob: Joi.date(),
        parentEmail: joiValidator.mail(),
        parentName: Joi.string(),
        address: Joi.string(), // deprecated, see #151839836
        phone: joiValidator.phone(),
        twitter: joiValidator.twitter(),
        linkedin: joiValidator.linkedin(),
        confidentMentoring: Joi.number(),
        confidentCoding: Joi.number(),
        reference: Joi.string().only(['search_engine', 'volunteers', 'organisations', 'developpers', 'events', 'word_of_mouth', 'family', 'media', 'other']),
        alternativeReference: Joi.string().optional(),
        isValid: Joi.boolean().required(),
        visited: Joi.boolean().required(),
      };
      let schema = Joi.object().keys(valid);
      if (required) {
        schema = schema.requiredKeys('firstName', 'lastName', 'email', 'dob',
          'phone', 'confidentCoding', 'confidentMentoring', 'reference');
      } else {
        schema = schema.optionalKeys('firstName', 'lastName', 'email', 'dob',
          'phone', 'confidentCoding', 'confidentMentoring', 'reference');
      }
      return schema;
    },
    // Even though it's a dojo, the name dojoLead is to differenciate from a finished dojo
    dojoLead(required) {
      const valid = {
        id: joiValidator.guid(),
        name: Joi.string(), // TODO: exclude Dojo from name
        firstSession: Joi.date(),
        frequency: joiValidator.frequency(),
        day: joiValidator.day().allow(null),
        startTime: Joi.string(),
        endTime: Joi.string(),
        alternativeFrequency: Joi.string().allow(null),
        requestEmail: Joi.boolean(),
        email: joiValidator.mail(),
        notes: Joi.string(),
        website: joiValidator.optionalUri(),
        twitter: joiValidator.twitter(),
        facebook: joiValidator.facebook(),
        isValid: Joi.boolean().required(),
        visited: Joi.boolean().required(),
      };
      let schema = Joi.object().keys(valid);
      const keys = ['name', 'firstSession', 'frequency', 'notes', 'requestEmail'];
      if (required) {
        keys.push('id');
        keys.push('isValid');
        schema = schema.requiredKeys(keys);
      } else {
        schema = schema.optionalKeys(keys)
          .requiredKeys('isValid');
      }
      return schema;
    },
    venue(required) {
      const valid = {
        isFound: Joi.boolean(),
        country: joiValidator.country(),
        place: joiValidator.place(),
        geoPoint: Joi.object({
          lat: Joi.number(),
          lon: Joi.number(),
        }),
        address1: Joi.string(),
        type: Joi.string().only(['office', 'public_space', 'tech_hub', 'library', 'maker_space', 'school', 'university', 'other']).allow(null),
        alternativeType: Joi.string().optional(),
        corporate: Joi.string(),
        alternativeCorporate: Joi.string().optional(),
        private: Joi.number().only(0, 1),
        isValid: Joi.boolean().required(),
        visited: Joi.boolean().required(),
      };
      let schema = Joi.object().keys(valid);
      const keys = ['isFound', 'country', 'geoPoint', 'type', 'address1', 'country', 'place'];

      if (required) {
        keys.push('isValid');
        schema = schema.requiredKeys(keys);
      } else {
        schema = schema.optionalKeys(keys)
          .requiredKeys('isValid');
      }
      return schema;
    },
    team() {
      return Joi.object().keys({
        status: Joi.string(),
        src: Joi.object().keys({
          community: Joi.boolean().allow(true),
          teachers: Joi.boolean().allow(true),
          pro: Joi.boolean().allow(true),
          students: Joi.boolean().allow(true),
          staff: Joi.boolean().allow(true),
          youth: Joi.boolean().allow(true),
          parents: Joi.boolean().allow(true),
          other: Joi.boolean().allow(true),
        }),
        alternativeSrc: Joi.string(),
        isValid: Joi.boolean().required(),
        visited: Joi.boolean().required(),
      });
    },
    charter() {
      const valid = {
        id: Joi.string(),
        fullName: Joi.string(),
        isValid: Joi.boolean().required(),
        visited: Joi.boolean().required(),
      };
      return Joi.object().keys(valid);
    },
    application(required) {
      const application = {
        champion: required ? joiValidator.champion(required).required() : joiValidator.champion(),
        dojo: required ? joiValidator.dojoLead(required).required() : joiValidator.dojoLead(),
        venue: required ? joiValidator.venue(required).required() : joiValidator.venue(),
        team: required ? joiValidator.team(required).required() : joiValidator.team(),
        charter: required ? joiValidator.charter(required).required() : joiValidator.charter(),
      };
      return Joi.object().keys(application);
    },
    user() {
      return Joi.object().keys({
        id: joiValidator.guid().required(),
        nick: Joi.string(),
        email: joiValidator.mail().required(),
        name: Joi.string().required(),
        username: Joi.any(),
        activated: Joi.any(),
        level: Joi.any(),
        mysqlUserId: Joi.any(),
        firstName: Joi.any(),
        lastName: Joi.any(),
        roles: Joi.array().required(),
        phone: Joi.any(),
        mailingList: Joi.any(),
        termsConditionsAccepted: Joi.any(),
        when: Joi.date(),
        confirmed: Joi.any(),
        admin: Joi.any(),
        modified: Joi.any(),
        locale: Joi.any(),
        banned: Joi.any(),
        banReason: Joi.any(),
        initUserType: Joi.object().keys({
          name: Joi.string(),
          title: Joi.string(),
        }),
        joinRequests: Joi.any(),
        lastLogin: Joi.date(),
        lmsId: Joi.any(),
        profileId: Joi.any(),
      });
    },
    guid() {
      return Joi.alternatives().try(Joi.string().guid(), Joi.string());
    },
  };
  return joiValidator;
};
Example #30
0
export const routes = {
    method: 'GET',
    path: '/api/worlds/{world}',
    config: {
        id: 'getWorld',
        description: 'Get a single World by it\'s unique ID',
        tags: ['api', 'world'],
        response: {
            failAction: 'log',
            options: {

            },
            schema: Joi.object().keys({
                name: Joi.string().required().description('The name of the world'),
                version: Joi.number().integer().required().description('The version number of the record'),
                created: Joi.date().iso().required().description('The timestamp of when the world was created'),
                updated: Joi.date().iso().description('The timestamp of when the world was last updated'),
                _links: Joi.object().keys({
                    self: Joi.object().keys({
                        href: Joi.string().uri().required()
                    })
                }),
                _embedded: Joi.object().keys({
                    owner: Joi.object().keys({
                        name: Joi.string().required().description('The name of the owner of this world'),
                        _links: Joi.object().keys({
                            self: Joi.object().keys({
                                href: Joi.string().uri().required()
                            })
                        })
                    })