constructor(props) { super(props); this.validatorTypes = { user: Joi.string().required().label('User'), password: Joi.string().allow(''), address: Joi.string().required(), database: Joi.string().required().label('Database'), port: Joi.number().integer().required().label('Port'), useSSH: Joi.boolean(), sshUser: Joi.alternatives().when('useSSH', { is: true, then: Joi.string().required(), otherwise: Joi.string().allow('') }), sshPassword: Joi.string().allow(''), sshServer: Joi.alternatives().when('useSSH', { is: true, then: Joi.string().required(), otherwise: Joi.string().allow('') }), sshPort: Joi.alternatives().when('useSSH', { is: true, then: Joi.number().integer().required(), otherwise: Joi.string().allow('') }) }; this.getValidatorData = this.getValidatorData.bind(this); this.getClasses = this.getClasses.bind(this); this.showDialog = this.showDialog.bind(this); this.setFavorit = this.setFavorit.bind(this); this.delFavorit = this.delFavorit.bind(this); this.getValue = this.getValue.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
describe('returns an array of valid objects', function () { var schema = Joi.object().keys({ amdPath: Joi.string().required(), name: Joi.string().required(), path: Joi.string().required(), doc: Joi.alternatives().try(Joi.string(), null), caniuse: Joi.alternatives().try(Joi.string(), null), async: Joi.boolean(), aliases: Joi.array().items(Joi.string()), builderAliases: Joi.array().items(Joi.string()), knownBugs: Joi.array().items(Joi.string()), warnings: Joi.array().items(Joi.string()), authors: Joi.array().items(Joi.string()), tags: Joi.array().items(Joi.string()), deps: Joi.array().items(Joi.string()), notes: Joi.array().items( Joi.object().keys({ name: Joi.string().required(), href: Joi.string().required() }) ).unique(), cssclass: Joi.alternatives().try( Joi.string().lowercase(), Joi.array().items(Joi.string().lowercase()) ).required(), property: Joi.alternatives().try( Joi.string().lowercase(), Joi.array().items(Joi.string().lowercase()) ).required(), polyfills: Joi.array().items( Joi.object().keys({ name: Joi.string().required(), authors: Joi.array().items(Joi.string()), notes: Joi.array().items(Joi.string()), href: Joi.string().required(), licenses: Joi.array().items(Joi.string()).required() }) ).unique() }); metadata(function (data) { data.forEach(function (obj) { var err = schema.validate(obj).error; it('for ' + obj.name, function () { expect(err).to.be(null); }); }); }); });
/** * Sends a notification. * @param {string|object} message the message to display to the recipient * @param {object} options a hash of options to pass to the API * @return {object} the response */ async sendNotification(message, options) { options = options || {}; // Perform some basic validation Joi.assert(message, Joi.alternatives().try(Joi.string(), Joi.object()).required(), new Error('`message` is required')); Joi.assert(options, Joi.object()); // Convert message to object as required by the API if (typeof message === 'string') { message = { en: message } } // Craft the payload const payload = Object.assign({ app_id: this.appId, contents: message }, options); // Make the request try { return await Request .post(`${API_URL}/notifications`) .set('Authorization', `Basic ${this.restApiKey}`) .send(payload); } catch(err) { throw new Error(err.response.error.text); } }
this.privilegeValidator = function (id, next) { if (!id) { return next(); } Joi.assert(id, Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())), 'Invalid data provided to hapi method'); var ids = []; if (!Array.isArray(id)) { ids.push(id); } else { ids = id; } var privileges = _this.getDbService().getAllPrivileges(); var count = 0; for (var i = 0; i < ids.length; i++) { if (privileges.indexOf(ids[i]) != -1) { count++; } } console.log(count); console.log('....'); console.log(ids.length); if (count == ids.length) { console.log('prashanth'); next(); } else { next(Boom.forbidden('Invalid privilege(s) provided')); } };
this.roleValidator = function (id, next) { if (!id) { return next(); } Joi.assert(id, Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())), 'Invalid data provided to hapi method'); var ids = []; if (!Array.isArray(id)) { ids.push(id); } else { ids = id; } _this.getDbService().getModel().find({ _id: { $in: ids } }, function (err, docs) { if (err) { next(Boom.badImplementation(err)); } else if (!docs) { next(Boom.forbidden('Invalid role id(s) provided')); } else { if (docs.length === ids.length) { next(); } else { next(Boom.forbidden('Invalid role id(s) provided')); } } }); };
timestamp: function (options) { var validator = joi.alternatives().meta({ cql: true, type: 'timestamp', default: options && options.default }).try( joi.number().integer(), joi.date().iso() ); return defaultify('date', validator, options); },
function resolveOneOf(current) { Assert.ok(Thing.isArray(current.oneOf), 'Expected allOf to be an array.'); return Joi.alternatives().try(current.oneOf.map(function (schema) { return resolve(schema); })).required(); }
function resolveAnyOf(current) { Assert.ok(Thing.isArray(current.anyOf), 'Expected anyOf to be an array.'); return Joi.alternatives().try(current.anyOf.map(function (schema) { return resolve(schema); })); }
function isAzureDevOpsTestTotals( passedLabel, failedLabel, skippedLabel, isCompact ) { const passedRegex = getLabelRegex(passedLabel, isCompact) const failedRegex = getLabelRegex(failedLabel, isCompact) const skippedRegex = getLabelRegex(skippedLabel, isCompact) const separator = isCompact ? ' | ' : ', ' const regexStrings = [ `^${passedRegex}$`, `^${failedRegex}$`, `^${skippedRegex}$`, `^${passedRegex}${separator}${failedRegex}$`, `^${failedRegex}${separator}${skippedRegex}$`, `^${passedRegex}${separator}${skippedRegex}$`, `^${passedRegex}${separator}${failedRegex}${separator}${skippedRegex}$`, `^no tests$`, ] return Joi.alternatives().try( regexStrings.map(regexStr => Joi.string().regex(new RegExp(regexStr))) ) }
/** * Validate options * @private */ function validate (opts = {}) { const schema = Joi.object().keys({ accessToken: Joi.string().required(), spaceId: Joi.string().required(), addDataTo: Joi.object().required(), json: Joi.string(), contentTypes: Joi.array().items( Joi.object().keys({ id: Joi.string(), name: Joi.string(), ordered: Joi.boolean().default(false), filters: Joi.object().keys({ limit: Joi.number().integer().min(1).max(100).default(100) }), transform: Joi.alternatives().try(Joi.boolean(), Joi.func()).default(true) }) ) }) const res = Joi.validate(opts, schema, { allowUnknown: true, language: { messages: { wrapArrays: false }, object: { child: '!![spike-contentful constructor] option {{reason}}' } } }) if (res.error) { throw new Error(res.error) } return res.value }
export function exportApi(server) { server.route({ path: '/api/kibana/dashboards/export', config: { validate: { query: Joi.object().keys({ dashboard: Joi.alternatives().try( Joi.string(), Joi.array().items(Joi.string()) ).required() }) }, tags: ['api'], }, method: ['GET'], handler: (req, reply) => { const currentDate = moment.utc(); return exportDashboards(req) .then(resp => { const json = JSON.stringify(resp, null, ' '); const filename = `kibana-dashboards.${currentDate.format('YYYY-MM-DD-HH-mm-ss')}.json`; reply(json) .header('Content-Disposition', `attachment; filename="${filename}"`) .header('Content-Type', 'application/json') .header('Content-Length', Buffer.byteLength(json, 'utf8')); }) .catch(err => reply(Boom.boomify(err, { statusCode: 400 }))); } }); }
module.exports = function(xml, _options) { _options = _options || {}; var parser = new expat.Parser('UTF-8'); parser.on('startElement', startElement); parser.on('text', text); parser.on('endElement', endElement); obj = currentObject = {}; ancestors = []; currentElementName = null; var schema = { object: joi.boolean().default(false), reversible: joi.boolean().default(false), coerce: joi.alternatives([joi.boolean(), joi.object()]).default(false), sanitize: joi.boolean().default(true), trim: joi.boolean().default(true), arrayNotation: joi.alternatives([joi.boolean(), joi.array()]).default(false), alternateTextNode: [joi.boolean().default(false), joi.string().default(false)] }; var validation = joi.validate(_options, schema); hoek.assert(validation.error === null, validation.error); options = validation.value; options.forceArrays = {}; if (Array.isArray(options.arrayNotation)) { options.arrayNotation.forEach(function(i) { options.forceArrays[i] = true; }); options.arrayNotation = false; } if (!parser.parse(xml)) { throw new Error('There are errors in your xml file: ' + parser.getError()); } if (options.object) { return obj; } var json = JSON.stringify(obj); //See: http://timelessrepo.com/json-isnt-a-javascript-subset json = json.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); return json; };
/** * Used for creating decimal with string and number alternative formats * * @param {String} name - the type of decimal value * @returns {Joi} - the validator */ function decimal(name) { return joi.alternatives().meta({ cql: true, type: name }).try( // a string that represents a number that is larger than JavaScript can handle joi.string().regex(/^\-?\d+(\.\d+)?$/m), // any number that can be represented in JavaScript joi.number() ); }
varint: function () { return joi.alternatives().meta({ cql: true, type: 'varint' }).try( // a string that represents a number that is larger than JavaScript can handle joi.string().regex(/^\-?\d+$/m), // any integer that can be represented in JavaScript joi.number().integer() ); },
static get validator () { return { name: Joi.string().required(), desc: Joi.string(), permissions: Joi.alternatives().try( Joi.object().required(), Joi.boolean().required() ) } };
Joi.one = function(resource) { var obj = Joi.alternatives().try( Joi.any().valid(null), // null ourJoi._joiBase(resource) ); obj._settings = { __one: resource }; return obj; };
Joi.belongsToOne = function(config) { Joi._validateForeignRelation(config); var obj = Joi.alternatives().try( Joi.any().valid(null), // null ourJoi._joiBase(config.resource) ); obj._settings = { __one: config.resource, __as: config.as }; return obj; };
function forProp(prop) { let typeSig = schemaUtil.getPropType(prop, schema).split(":"); if (typeSig[0] !== "array") { let targetType = getTargetType(typeSig); return Joi.alternatives().try([ targetType, Joi.object().keys({ $ne: targetType }), ]); } else { return getTargetType(typeSig); } }
function _generateSchema(keys) { var mapped = {}; _.each(keys, function (key) { mapped[key] = Joi.object(_singleDBSchema).required(); }); _.each(_.keys(_singleDBSchema), function (key) { mapped[key] = Joi.any().forbidden(); }); var validationSchema = Joi.alternatives([ Joi.object(_singleDBSchema).required(), Joi.object().keys(mapped) ]); return validationSchema; }
set: function (type) { var meta = findMeta(type); var set = joi.array().sparse(false).unique().items(type); return joi.alternatives().meta({ cql: true, type: 'set', setType: meta.type, serialize: convertArray(meta.serialize), deserialize: convertArray(meta.deserialize) }).try(set, joi.object().keys({ add: set, remove: set }).or('add', 'remove').unknown(false)); },
exports.view = function (options) { var schema = internals.viewSchema({ module: Joi.alternatives([ Joi.object({ compile: Joi.func().required() }).options({ allowUnknown: true }), Joi.string() ]).required() }); var error = Joi.validate(options, schema); return (error ? error.annotated() : null); };
const getKibanaSchema = () => { const privileges = authorization.privileges.get(); const allSpacesSchema = Joi.array().length(1).items(Joi.string().valid([GLOBAL_RESOURCE])); return Joi.array().items( Joi.object({ base: Joi.alternatives().when('spaces', { is: allSpacesSchema, then: Joi.array().items(Joi.string().valid(Object.keys(privileges.global))).empty(Joi.array().length(0)), otherwise: Joi.array().items(Joi.string().valid(Object.keys(privileges.space))).empty(Joi.array().length(0)), }), feature: Joi.object() .pattern(/^[a-zA-Z0-9_-]+$/, Joi.array().items(Joi.string().regex(/^[a-zA-Z0-9_-]+$/))) .empty(Joi.object().length(0)), spaces: Joi.alternatives( allSpacesSchema, Joi.array().items(Joi.string().regex(/^[a-z0-9_-]+$/)), ).default([GLOBAL_RESOURCE]), }) // the following can be replaced with .oxor once we upgrade Joi .without('base', ['feature']) ).unique((a, b) => { return intersection(a.spaces, b.spaces).length !== 0; }); };
list: function (type) { var meta = findMeta(type); var list = joi.array().sparse(false).items(type); return joi.alternatives().meta({ cql: true, type: 'list', listType: meta.type, serialize: convertArray(meta.serialize), deserialize: convertArray(meta.deserialize) }).try(list, joi.object().keys({ prepend: list, append: list, remove: list, index: joi.object().pattern(/^\d+$/, type) }).or('prepend', 'append', 'remove', 'index').unknown(false)); }
it('omits forbidden fields', () => { const schema = joiql({ query: { a: string().forbidden(), b: string(), c: object({ d: string().forbidden(), e: string() }), f: array().items(object({ g: string().forbidden(), h: string() })), j: array().items( object({ k: string() }), object({ l: string() }).forbidden() ), m: alternatives( object({ n: string() }).meta({ name: 'N' }), object({ o: string() }).meta({ name: 'O' }).forbidden() ) } }) return graphql(schema, '{ a c { d } f { g } j { k l } m { o } }') .then((res) => { const errs = res.errors.map((e) => e.message).join('') errs.should.containEql('Cannot query field "a"') errs.should.containEql('Cannot query field "d"') errs.should.containEql('Cannot query field "g"') errs.should.containEql('Cannot query field "l"') errs.should.containEql('Cannot query field "o"') }) .then(() => graphql(schema, '{ a b c { e } f { h } j { k } m ... on N { n } }') ) .then((res) => { const errs = res.errors.map((e) => e.message).join('') errs.should.not.containEql('Cannot query field "b"') errs.should.not.containEql('Cannot query field "e"') errs.should.not.containEql('Cannot query field "h"') errs.should.not.containEql('Cannot query field "k"') errs.should.not.containEql('Cannot query field "n"') }) })
it('omits forbidden args', () => { const schema = joiql({ query: { a: string().meta({ args: { b: string().forbidden(), c: string(), d: object({ e: string().forbidden(), f: string() }), g: array().items(object({ h: string().forbidden(), i: string() })), j: array().items( object({ k: string() }), object({ l: string() }).forbidden() ), m: alternatives( object({ n: string() }).meta({ name: 'N' }), object({ o: string() }).meta({ name: 'O' }).forbidden() ) } }) } }) return graphql(schema, `{ a( b: "Foo" d: { e: "Foo" } g: { h: "Foo" } j: { l: "Foo" } m: { o: "Foo" } ) }`).then((res) => { const errs = res.errors.map((e) => e.message).join('') errs.should.containEql('Unknown argument "b"') errs.should.containEql('has invalid value {e') errs.should.containEql('has invalid value {h') errs.should.containEql('has invalid value {l') errs.should.containEql('has invalid value {o') }) })
module.exports = () => ({ method: 'GET', path: '/templates/{name}/{versionOrTag}', config: { description: 'Get a single template given template name and version or tag', notes: 'Returns a template record', tags: ['api', 'templates'], auth: { strategies: ['token'], scope: ['user', 'build'] }, plugins: { 'hapi-swagger': { security: [{ token: [] }] } }, handler: (request, reply) => { const templateFactory = request.server.app.templateFactory; const { name, versionOrTag } = request.params; return templateFactory.getTemplate(`${name}@${versionOrTag}`) .then((template) => { if (!template) { throw boom.notFound(`Template ${name}@${versionOrTag} does not exist`); } return reply(template); }) .catch(err => reply(boom.boomify(err))); }, response: { schema: getSchema }, validate: { params: { name: nameSchema, versionOrTag: joi.alternatives().try( versionSchema, tagSchema ) } } } });
function generateSchema() { const topLevelKeys = { servers: joi.object().required(), app: joi.object(), plugins: joi.array(), hooks: joi.object().pattern(/.*/, joi.alternatives(joi.object({ localCommand: joi.string(), remoteCommand: joi.string(), method: joi.func() }), joi.func() )) }; Object.keys(_pluginValidators).forEach(key => { topLevelKeys[key] = joi.any(); }); return joi.object().keys(topLevelKeys); }
.then(() => server.route({ method: 'POST', path, options: { payload: { output: 'data', parse: true }, validate: { payload: joi.object({ jsonrpc: joi.string().valid('2.0').required(), timeout: joi.number().optional(), id: joi.alternatives().try(joi.number().example(1), joi.string().example('1')), method: joi.string().required(), params: joi.array().required() }) } }, handler }));
getGist: function (req, done) { let schema = Joi.object().keys({ gist: Joi.alternatives([Joi.string().uri(), Joi.object().keys({ gist_url: Joi.string().uri(), gist_version: Joi.strict() })]), repoId: Joi.number(), orgId: Joi.number(), repo: Joi.string(), owner: Joi.string() }); Joi.validate(req.args, schema, { abortEarly: false }, function (joiErr) { if (joiErr) { joiErr.code = 400; return done(joiErr); } if (req.user && req.user.token && req.args.gist) { cla.getGist({ token: req.user.token, gist: req.args.gist }, done); } else { let service = req.args.orgId ? orgService : repoService; service.get(req.args, function (err, item) { if (err || !item) { log.warn(err.stack + 'with args: ' + req.args); done(err); return; } let gist_args = { gist_url: item.gist }; gist_args = req.args.gist ? req.args.gist : gist_args; token = item.token; cla.getGist({ token: token, gist: gist_args }, done); }); } }); },
validate: function validateOptions(fn) { var valid = joi.object({ currentPath: joi.string().allow('').default(''), defaultOptions: joi.object().default({}), defaultPolicies: joi.array().items(joi.string(), joi.func()).default([]), definition: joi.alternatives().try(joi.object(), joi.string()).required(), isRegex: joi.boolean().default(false), //path: joi.string().default(''), regexPathDefinition: joi.string().allow('').default(''), routes: joi.object().default({}), version: joi.string().regex(/^v?\d+\.\d+\.\d+$/).default('1.0.0') }).required(); joi.validate(options, valid, {}, function(err, validated) { if (err) { return fn(err); } options = validated; fn(); }); },