request_id: Joi.number().required(), method: Joi.only('token', 'anonymous', 'unauthenticated').required(), token: Joi.string().required() .when('method', { is: Joi.not('token').required(), then: Joi.forbidden() }), }).unknown(false); const read = Joi.alternatives().try( Joi.object().keys({ collection: Joi.string().token().required(), find: Joi.object().min(1).unknown(true).required(), }).unknown(false), Joi.object().keys({ collection: Joi.string().token().required(), limit: Joi.number().integer().greater(-1).optional() .when('find', { is: Joi.any().required(), then: Joi.forbidden() }), order: Joi.array().ordered( Joi.array().items(Joi.string()).min(1).unique().label('fields').required(), Joi.string().valid('ascending', 'descending').label('direction').required()).optional() .when('find_all', { is: Joi.array().min(2).required(), then: Joi.forbidden() }), above: Joi.array().ordered( Joi.object().length(1).unknown(true).label('value').required(), Joi.string().valid('open', 'closed').label('bound_type').required()).optional() .when('find_all', { is: Joi.array().min(2).required(), then: Joi.forbidden() }), below: Joi.array().ordered( Joi.object().length(1).unknown(true).label('value').required(), Joi.string().valid('open', 'closed').label('bound_type').required()).optional() .when('find_all', { is: Joi.array().min(2).required(), then: Joi.forbidden() }),
method: 'GET', path: '/withconditionalalternatives', config: { handler: handler, validate: { query: { param1: t.alternatives() .when('b', { is: 5, then: t.string(), otherwise: t.number() }) .when('a', { is: true, then: t.date(), otherwise: t.any() }) } } } }, { method: 'GET', path: '/withreferences', config: { handler: handler, validate: { query: { param1: t.ref('a.b'), param2: t.ref('$x') } }
}), maxSockets: Joi.number().positive().allow(false) }); internals.vhost = Joi.alternatives([ Joi.string().hostname(), Joi.array().includes(Joi.string().hostname()).min(1) ]); internals.route = Joi.object({ method: Joi.alternatives(Joi.string(), Joi.array().includes(Joi.string()).min(1)).required(), path: Joi.string().required(), vhost: internals.vhost, handler: Joi.any(), // Validated in route.config config: Joi.object().allow(null) }); internals.pre = [ Joi.string(), Joi.func(), Joi.object({ method: Joi.alternatives(Joi.string(), Joi.func()).required(), assign: Joi.string(), mode: Joi.string().valid('serial', 'parallel'), failAction: Joi.string().valid('error', 'log', 'ignore') }) ];
import Joi from 'joi'; import { middleware as tcMiddleware } from 'tc-core-library-js'; import util from '../../../util'; import models from '../../../models'; const permissions = tcMiddleware.permissions; const schema = { params: { key: Joi.string().max(45).required(), }, body: { param: Joi.object().keys({ config: Joi.object().required(), createdAt: Joi.any().strip(), updatedAt: Joi.any().strip(), deletedAt: Joi.any().strip(), createdBy: Joi.any().strip(), updatedBy: Joi.any().strip(), deletedBy: Joi.any().strip(), }).required(), }, }; module.exports = [ validate(schema), permissions('form.create'), (req, res, next) => { models.sequelize.transaction(() => models.Form.findAll({ where: {
payload: [ Joi.string().valid('required', 'optional'), Joi.boolean() ] }) .without('strategy', 'strategies') .without('access', ['scope', 'entity']) ]); internals.event = Joi.object({ method: Joi.array().items(Joi.func()).single(), options: Joi.object({ before: Joi.array().items(Joi.string()).single(), after: Joi.array().items(Joi.string()).single(), bind: Joi.any(), sandbox: Joi.string().valid('connection', 'plugin') }) .default({}) }); internals.exts = Joi.array().items(internals.event.keys({ type: Joi.string().required() })).single(); internals.routeBase = Joi.object({ app: Joi.object().allow(null), auth: internals.auth.allow(false), bind: Joi.object().allow(null), cache: Joi.object({ expiresIn: Joi.number(),
const _ = require('lodash') const joi = require('joi') const runtimeConfig = require('../../models/runtimeConfig') const joiValidate = require('../../utils/joiValidate') const bodySchema = { strict: joi.boolean(), active: joi.boolean(), recording: joi.boolean(), dump: joi.boolean(), sleep: joi.number().integer().max(10), retryLockTimeout: joi.number().integer().max(10), disabledProjects: joi.array().items( joi.string().lowercase().token().max(64), joi.any().strip() ) } module.exports = function * () { const body = joiValidate(this.request.body, bodySchema) if (body.disabledProjects !== undefined) { body.disabledProjects = _.sortedUniq(body.disabledProjects || []) } body.sleep = Math.max(body.sleep || 0, 0) body.retryLockTimeout = Math.max(body.retryLockTimeout || 0, 0) yield runtimeConfig.set(body) this.body = null }
module.exports = () => Joi.object({ pkg: Joi.object({ version: Joi.string().default(Joi.ref('$version')), buildNum: Joi.number().default(Joi.ref('$buildNum')), buildSha: Joi.string().default(Joi.ref('$buildSha')), }).default(), env: Joi.object({ name: Joi.string().default(Joi.ref('$env')), dev: Joi.boolean().default(Joi.ref('$dev')), prod: Joi.boolean().default(Joi.ref('$prod')) }).default(), dev: Joi.object({ basePathProxyTarget: Joi.number().default(5603), }).default(), pid: Joi.object({ file: Joi.string(), exclusive: Joi.boolean().default(false) }).default(), uuid: Joi.string().guid().default(), server: Joi.object({ name: Joi.string().default(os.hostname()), host: Joi.string().hostname().default('0.0.0.0'), port: Joi.number().default(5601), maxPayloadBytes: Joi.number().default(1048576), autoListen: Joi.boolean().default(true), defaultRoute: Joi.string().default('/app/kibana').regex(/^\//, `start with a slash`), basePath: Joi.string().default('').allow('').regex(/(^$|^\/.*[^\/]$)/, `start with a slash, don't end with one`), ssl: Joi.object({ cert: Joi.string(), key: Joi.string() }).default(), cors: Joi.when('$dev', { is: true, then: Joi.object().default({ origin: ['*://localhost:9876'] // karma test server }), otherwise: Joi.boolean().default(false) }), xsrf: Joi.object({ disableProtection: Joi.boolean().default(false), token: Joi.string().optional().notes('Deprecated') }).default(), }).default(), logging: Joi.object().keys({ silent: Joi.boolean().default(false), quiet: Joi.boolean() .when('silent', { is: true, then: Joi.default(true).valid(true), otherwise: Joi.default(false) }), verbose: Joi.boolean() .when('quiet', { is: true, then: Joi.valid(false).default(false), otherwise: Joi.default(false) }), events: Joi.any().default({}), dest: Joi.string().default('stdout'), filter: Joi.any().default({}), json: Joi.boolean() .when('dest', { is: 'stdout', then: Joi.default(!process.stdout.isTTY), otherwise: Joi.default(true) }) }) .default(), ops: Joi.object({ interval: Joi.number().default(5000), }).default(), plugins: Joi.object({ paths: Joi.array().items(Joi.string()).default([]), scanDirs: Joi.array().items(Joi.string()).default([]), initialize: Joi.boolean().default(true) }).default(), path: Joi.object({ data: Joi.string().default(getData()) }).default(), optimize: Joi.object({ enabled: Joi.boolean().default(true), bundleFilter: Joi.string().default('!tests'), bundleDir: Joi.string().default(fromRoot('optimize/bundles')), viewCaching: Joi.boolean().default(Joi.ref('$prod')), lazy: Joi.boolean().default(false), lazyPort: Joi.number().default(5602), lazyHost: Joi.string().hostname().default('localhost'), lazyPrebuild: Joi.boolean().default(false), lazyProxyTimeout: Joi.number().default(5 * 60000), useBundleCache: Joi.boolean().default(Joi.ref('$prod')), unsafeCache: Joi .alternatives() .try( Joi.boolean(), Joi.string().regex(/^\/.+\/$/) ) .default('/[\\/\\\\](node_modules|bower_components)[\\/\\\\]/'), sourceMaps: Joi .alternatives() .try( Joi.string().required(), Joi.boolean() ) .default(Joi.ref('$dev')), profile: Joi.boolean().default(false) }).default(), status: Joi.object({ allowAnonymous: Joi.boolean().default(false) }).default(), tilemap: Joi.object({ url: Joi.string().default(`https://tiles.elastic.co/v1/default/{z}/{x}/{y}.png?my_app_name=kibana&my_app_version=${pkg.version}&elastic_tile_service_tos=agree`), options: Joi.object({ attribution: Joi.string().default('© [Elastic Tile Service](https://www.elastic.co/elastic-tile-service)'), minZoom: Joi.number().min(1, 'Must not be less than 1').default(1), maxZoom: Joi.number().default(10), tileSize: Joi.number(), subdomains: Joi.array().items(Joi.string()).single(), errorTileUrl: Joi.string().uri(), tms: Joi.boolean(), reuseTiles: Joi.boolean(), bounds: Joi.array().items(Joi.array().items(Joi.number()).min(2).required()).min(2) }).default() }).default() }).default();
import Joi from 'joi' import { notAbsolutePath, looksLikeAbsolutePath, urlPart } from '../../types' export default Joi.object({ filename: notAbsolutePath, // don't check for existence here because it could be created in the build process path: looksLikeAbsolutePath, publicPath: Joi.alternatives().try([ urlPart, Joi.string().valid(''), ]), chunkFilename: notAbsolutePath, sourceMapFilename: notAbsolutePath, devtoolModuleFilenameTemplate: [notAbsolutePath, Joi.func()], devtoolFallbackModuleFilenameTemplate: [notAbsolutePath, Joi.func()], devtoolLineToLine: Joi.any(), hashDigestLength: Joi.number(), hotUpdateChunkFilename: notAbsolutePath, hotUpdateMainFilename: notAbsolutePath, jsonpFunction: Joi.string(), hotUpdateFunction: Joi.string(), pathinfo: Joi.bool(), library: [notAbsolutePath, Joi.array().items(Joi.string())], libraryTarget: Joi.string().valid(['var', 'this', 'commonjs', 'commonjs2', 'amd', 'umd']), umdNamedDefine: Joi.bool(), sourcePrefix: Joi.string(), crossOriginLoading: Joi.alternatives().try([ Joi.bool().valid(false), Joi.string().valid(['anonymous', 'use-credentials']), ]).options({ language: { boolean: { base: 'should be `false`, "anonymous" or "use-credentials"' } } }),
module.exports = () => Joi.object({ pkg: Joi.object({ version: Joi.string().default(Joi.ref('$version')), buildNum: Joi.number().default(Joi.ref('$buildNum')), buildSha: Joi.string().default(Joi.ref('$buildSha')), }).default(), env: Joi.object({ name: Joi.string().default(Joi.ref('$env')), dev: Joi.boolean().default(Joi.ref('$dev')), prod: Joi.boolean().default(Joi.ref('$prod')) }).default(), dev: Joi.object({ basePathProxyTarget: Joi.number().default(5603), }).default(), pid: Joi.object({ file: Joi.string(), exclusive: Joi.boolean().default(false) }).default(), server: Joi.object({ host: Joi.string().hostname().default('0.0.0.0'), port: Joi.number().default(5601), maxPayloadBytes: Joi.number().default(1048576), autoListen: Joi.boolean().default(true), defaultRoute: Joi.string(), basePath: Joi.string().default('').allow('').regex(/(^$|^\/.*[^\/]$)/, `start with a slash, don't end with one`), ssl: Joi.object({ cert: Joi.string(), key: Joi.string() }).default(), cors: Joi.when('$dev', { is: true, then: Joi.object().default({ origin: ['*://localhost:9876'] // karma test server }), otherwise: Joi.boolean().default(false) }), xsrf: Joi.object({ disableProtection: Joi.boolean().default(false), token: Joi.string().optional().notes('Deprecated') }).default(), }).default(), logging: Joi.object().keys({ silent: Joi.boolean().default(false), quiet: Joi.boolean() .when('silent', { is: true, then: Joi.default(true).valid(true), otherwise: Joi.default(false) }), verbose: Joi.boolean() .when('quiet', { is: true, then: Joi.valid(false).default(false), otherwise: Joi.default(false) }), events: Joi.any().default({}), dest: Joi.string().default('stdout'), filter: Joi.any().default({}), json: Joi.boolean() .when('dest', { is: 'stdout', then: Joi.default(!process.stdout.isTTY), otherwise: Joi.default(true) }) }) .default(), plugins: Joi.object({ paths: Joi.array().items(Joi.string()).default([]), scanDirs: Joi.array().items(Joi.string()).default([]), initialize: Joi.boolean().default(true) }).default(), optimize: Joi.object({ enabled: Joi.boolean().default(true), bundleFilter: Joi.string().default('!tests'), bundleDir: Joi.string().default(fromRoot('optimize/bundles')), viewCaching: Joi.boolean().default(Joi.ref('$prod')), lazy: Joi.boolean().default(false), lazyPort: Joi.number().default(5602), lazyHost: Joi.string().hostname().default('localhost'), lazyPrebuild: Joi.boolean().default(false), lazyProxyTimeout: Joi.number().default(5 * 60000), useBundleCache: Joi.boolean().default(Joi.ref('$prod')), unsafeCache: Joi .alternatives() .try( Joi.boolean(), Joi.string().regex(/^\/.+\/$/) ) .default('/[\\/\\\\](node_modules|bower_components)[\\/\\\\]/'), sourceMaps: Joi .alternatives() .try( Joi.string().required(), Joi.boolean() ) .default(Joi.ref('$dev')), profile: Joi.boolean().default(false) }).default() }).default();
describe(key + '-Mapper', function() { User.schema.id = Joi.any() this.timeout(10000); var userMapper; var id; var email = "*****@*****.**"; var user; var mail; var Mapper; before(function(done) { promise.then(function(mappers) { Mapper = mappers[key]; userMapper = new Mapper(User); id = Mapper.generateId(); mail = id + '@test.com';1 user = new User({ id: id, name: "test1", age: 31, hash: "testtesttesttesttesttesttesttesttesttesttest", mail: mail}); done(); }); }); it('Save a user', function(done) { userMapper.create(user, { sk: 'mail' }) .then(function(user2) { expect(user2).instanceof(User); expect(user2.get('name')).equals('test1'); done(); }).catch(done) }); it('Update a user', function(done) { userDelta = { name: "test1", age: 62, hash: "TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTES3"}; user.merge(userDelta) userMapper.update(user) .then(function(user2) { expect(user2).instanceof(User); expect(userDelta.age).equals(user2.get('age')); done(); }).catch(done) }); it('Save a user with no id', function(done) { user = new User({ name: "test2", age: 13, hash: "testtesttesttesttesttesttesttesttesttesttest"}); userMapper.create(user) .then(function(user2) { expect(user2).instanceof(User); expect(user2.get('name')).equals('test2'); done(); }).catch(done) }); it('Retreive a user from primary key, then directly update using model', function(done) { userMapper.get(id) .then(function(user2) { user2.set('age', 54); expect(user2).instanceof(User); return userMapper.update(user2); }).then( function(user3) { expect(user3).instanceof(User); expect(user3.get('age')).equals(54); done(); }).catch(done) }); it('Retreive a user from secondary key', function(done) { userMapper.findOne({ mail: mail }) .then(function(user2) { expect(user2).instanceof(User); expect(user2.get('id').toString() == id.toString()).equal(true); done(); }).catch(done) }); it('Retreive a non-existant user from primary', function(done) { userMapper.get("lalala") .then(function(user2) { expect(user2).to.satisfy(function() { return user2 == null || user2 == undefined } ); done(); }).catch(done) }); it('Retreive a non-existant user from secondary key', function(done) { userMapper.findOne({ mail: "*****@*****.**" }) .then(function(user2) { expect(user2).to.satisfy(function() { return user2 == null || user2 == undefined } ); done(); }).catch(done) }); after(function(done) { //if(mappers.length > 0) next(mappers.pop()) done(); }); });
spot.save(function (err, doc) { if (err) { return reply(Boom.badImplementation(err)); } reply(doc).created('/spots/' + doc.id); }); }, validate: { payload: { roads: Joi.array().items(Joi.object().keys({ id: Joi.string().required(), kilometer: Joi.number().required() })).required(), location: Joi.string().default(''), type: Joi.any().valid(['ordinary', 'fork', 'trafficLight', 'toll']).required(), redLight: Joi.alternatives().when('type', { is: 'trafficLight', then: Joi.object().keys({ duration: Joi.number().required(), frequency: Joi.number().required() }).required() }), toll: Joi.alternatives().when('type', { is: 'toll', then: Joi.object().keys({ serviceRate: Joi.number().required(), numberOfServers: Joi.number().required() }).required() }) }
module.exports = (server, options) => { return [ // - Basic CRUD - { method: 'GET', path: '/beers/{id}', config: { description: 'Get a beer', tags: ['api'], validate: { params: { id: Joi.any().required() } }, auth: false }, handler: function (request, reply) { const Beers = request.models().Beers; Beers.query().findById(request.params.id).asCallback((beerErr, foundBeer) => { if (beerErr) { return reply(Boom.wrap(beerErr)); } if (!foundBeer) { return reply(Boom.notFound('Beer not found.')); } reply(foundBeer); }); } }, { method: 'GET', path: '/beers', config: { description: 'Get all beers', tags: ['api'], auth: false }, handler: (request, reply) => { const Beers = request.models().Beers; Beers.query().asCallback((schoolErr, foundBeer) => { if (schoolErr){ return reply(Boom.wrap(schoolErr)); } return reply(foundBeer); }); } }, { method: 'GET', path: '/beers/on-tap', config: { description: 'Get all beers on tap', tags: ['api'], auth: false }, handler: (request, reply) => { return reply([{ id: 1, name: 'CloneZone IPA', abv: 6.3, ibus: 79, description: 'Galaxy and Mosaic hops contributes delicious citrusy and tropical flavor. Pleasantly hoppy with a dry finish that makes it endlessly enjoyable.', image_url: '', type: 'home-brew', brewery: { name: 'Brother\'s basement', image_url: '' }, clone_beer: { name: 'Ozone IPA', image_url: '', brewery: { name: 'Orono Brewing Company', image_url: '' } } }]); const Beers = request.models().Beers; Beers.query().asCallback((schoolErr, foundBeer) => { if (schoolErr){ return reply(Boom.wrap(schoolErr)); } return reply(foundBeer); }); } }, { method: 'POST', path: '/beers', config: { tags: ['api'], description: 'Register new beer', validate: { payload: { name: Joi.string().required(), description: Joi.string(), breweryId: Joi.number(), abv: Joi.number(), ibus: Joi.number(), description: Joi.string() } }, auth: false//TODO lock down, but leave for dev }, handler: (request, reply) => { const Beers = request.models().Beers; Beers.query().insert(request.payload) .asCallback((error, newBeer) => { if (error){ return reply(Boom.wrap(error)); } return reply().code(201); }); } } ]; };
const db = require('../../db'); const logger = require('../../logging')('routes.client.get'); const validators = require('../../validators'); /*jshint camelcase: false*/ module.exports = { validate: { params: { client_id: validators.clientId } }, response: { schema: { id: validators.clientId, name: Joi.string().required(), image_uri: Joi.any(), redirect_uri: Joi.string().required().allow('') } }, handler: function requestInfoEndpoint(req, reply) { var params = req.params; db.getClient(Buffer(params.client_id, 'hex')).then(function(client) { if (!client) { logger.debug('notFound', { id: params.client_id }); throw AppError.unknownClient(params.client_id); } return client; }).done(function(client) { reply({ id: hex(client.id), name: client.name,
res.json({success: true}); } }); }; exports.passwordGet = function(req, res) { res.render('controlpanel/user/password', { config: config, result: req.user, user: req.user }); }; exports.passwordSchemaPost = { password: Joi.string().min(8).required(), new_password: Joi.string().min(8).required(), new_password_confirm: Joi.any().valid(Joi.ref('new_password')).required() }; exports.passwordPost = function(req, res) { req.user.comparePassword(req.body.password, function(err, isMatch) { if (isMatch) { User.findById(req.user._id, function(err, user) { user.password = req.body.new_password; user.save(function() { _h.mail.sendPasswordChangedMail(user.primaryEmail.email); res.render('controlpanel/user/password', { config: config, alerts: [{ type: 'success', msg: __('Password changed') }], result: user,
var editActivityTypeConfiguration = module.exports.editActivityTypeConfiguration = function(ctx, activityTypeUpdates, callback) { // Only instructors are able to edit the activity type configuration if (!ctx.user.is_admin) { log.error({'id': ctx.user.id}, 'Unauthorized to edit the activity type configuration'); return callback({'code': 401, 'msg': 'Unauthorized to edit the activity type configuration'}); } // Parameter validation var validationSchema = Joi.array().min(1).items(Joi.object().min(2).keys({ 'type': Joi.any().valid(_.map(ActivitiesDefaults, 'type')).required(), 'points': Joi.number().optional(), 'enabled': Joi.boolean().optional() })); var validationResult = Joi.validate(activityTypeUpdates, validationSchema); if (validationResult.error) { return callback({'code': 400, 'msg': validationResult.error.details[0].message}); } // Get the current activity type overrides from the database getActivityTypeOverrides(ctx.course.id, function(err, activityTypeOverrides) { if (err) { return callback(err); } var upsertError = null; // Recalculate the points for each user in the course once each activity type override // is persisted var done = _.after(activityTypeUpdates.length, function() { recalculatePoints(ctx.course, null, function(err) { if (err) { return callback(err); } else if (upsertError) { return callback(upsertError); } return callback(); }); }); _.each(activityTypeUpdates, function(update) { // Construct an override object var activityTypeOverride = _.pick(update, ['type', 'points', 'enabled']); activityTypeOverride.course_id = ctx.course.id; // Get the previous override (if any) var override = _.find(activityTypeOverrides, {'type': update.type}); if (override) { activityTypeOverride.id = override.id; } // Create or update the activity type override DB.ActivityType.upsert(activityTypeOverride).complete(function(err) { if (err) { log.error({'type': err}, 'Failed to edit the configuration for an activity type'); upsertError = {'code': 500, 'msg': err.message}; // Even if an error occurs, the points have to be recalculated as some activity type // overrides might've been persisted } done(); }); }); }); };
/** * default data for swagger root object */ builder.default = { 'swagger': '2.0', 'host': 'localhost', 'basePath': '/' }; /** * schema for swagger root object */ builder.schema = Joi.object({ swagger: Joi.string().valid('2.0').required(), info: Joi.any(), host: Joi.string(), // JOI hostname validator too strict basePath: Joi.string().regex(/^\//), schemes: Joi.array().items(Joi.string().valid(['http', 'https', 'ws', 'wss'])).optional(), consumes: Joi.array().items(Joi.string()), produces: Joi.array().items(Joi.string()), paths: Joi.any(), definitions: Joi.any(), parameters: Joi.any(), responses: Joi.any(), securityDefinitions: Joi.any(), security: Joi.any(), tags: Joi.any(), externalDocs: Joi.object({ description: Joi.string(), url: Joi.string().uri()
'use strict'; var Joi = require( 'joi' ); module.exports = { 'id' : Joi.string().guid().required().description( 'The evidence id' ), 'type' : Joi.any().valid( [ 3, 4, 5, 6, 7, 8 ] ).required().description( 'The evidence type (e.g. 3 for file, 4 for comment, 5 for image, 6 for counter, 7 for timer, 8 for scripting' ), 'name' : Joi.string().required().description( 'The evidence name' ), 'description' : Joi.string().optional().description( 'The evidence description' ), 'url' : Joi.string().optional().description( 'The evidence location' ), 'scope' : Joi.string().required().description( 'The scope of the evidence' ), 'timestamp' : Joi.string().optional().description( 'When the evidence was assigned' ) };
.reduce(batch.payload.requests, function (responses, request) { return inject(request, batch) .bind(responses) .then(responses.push) .return(responses); }, []); } responses.done(reply); }; exports.validate = joi.object().keys({ parallel: joi.boolean(), requests: joi.array().required().min(1).includes(joi.object().keys({ path: joi.string().required(), payload: joi.any(), method: joi.string().default('get') })) }); function inject (request, batch) { return batch.server.injectThen({ url: request.path, method: request.method, headers: batch.headers, payload: JSON.stringify(request.payload), session: batch.session }) .get('result'); }
import Joi from "joi"; import PooshError from "poosh-common/lib/errors/PooshError"; const OPTIONS_SCHEMA = Joi.object().keys({ acl : Joi.any().valid([ "private", "public-read", "public-read-write", "authenticated-read", "aws-exec-read", "bucket-owner-read", "bucket-owner-full-control" ]), storageClass : Joi.any().valid([ "STANDARD", "REDUCED_REDUNDANCY", "STANDARD_IA"]) }); const JOI_OPTIONS = { abortEarly : false, convert : false, noDefaults : true }; /** * Validate and normalize file's remote options. * * @param options * @returns Normalized file's remote options. */
'use strict'; const fetch = require('node-fetch'); const Joi = require('joi'); const JwtSingin = require("../security/auth_jwt_signin"); var internal = {}; internal.tokenSigninSchema = Joi.object().keys({ iss: Joi.any().valid(['accounts.google.com', 'https://accounts.google.com']), aud: Joi.string().valid(GoogleProviders.aud), exp: Joi.date().timestamp('unix'), email: Joi.string().email(), picture: Joi.string().uri({ scheme: [ 'http', 'https']}), name: Joi.string(), given_name: Joi.string(), family_name: Joi.string(), locale: Joi.string(), }).with('iss', 'aud', 'exp'); internal.tokenSigninValidateOptions ={ abortEarly: true, convert: true, allowUnknown: true, skipFunctions: true }; internal.tokenSigninValidate = function(response) {
errors.ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF.code, errors.ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS.code ].indexOf(e.errorNum) !== -1) { throw Object.assign( new httperr.BadRequest(e.errorMessage), {errorNum: e.errorNum, cause: e} ); } throw e; } setResponse(res, 'graph', graphForClient(g), waitForSync ? CREATED : ACCEPTED); }) .queryParam('waitForSync', waitForSyncFlag) .body(joi.object({ name: joi.string().required(), edgeDefinitions: joi.any().optional(), orphanCollections: joi.any().optional() }).required(), 'The required information for a graph') .error('bad request', 'Graph creation error.') .error('conflict', 'Graph creation error.') .summary('Creates a new graph') .description('Creates a new graph object'); router.get('/:graph', function(req, res) { const name = req.pathParams.graph; let g; try { g = Graph._graph(name); } catch (e) { if (e.isArangoError && e.errorNum === errors.ERROR_GRAPH_NOT_FOUND.code) {
/*jshint node: true */ 'use strict'; const exacttarget = require('./exacttarget_helper'); const Joi = require('joi'); const mongodb = require('./mongodb_client.js'); const newsletter_schema = { _id: Joi.string().strip(), ident: Joi.string().alphanum(), last_modified: Joi.any().strip(), last_checksum: Joi.any().strip(), incomplete: Joi.any().strip(), name: Joi.string().min(1).max(255), identity: Joi.any().strip(), list: Joi.any().strip(), folder_id: [Joi.number(), Joi.string().allow('').max(100)], context_id: Joi.string().allow('').max(100), categories: Joi.array().items(Joi.string().min(1).max(100)), bond_url: Joi.string().uri({scheme: ['http', 'https']}), template_html: Joi.string().min(1).max(100), template_plain: Joi.strip(), tags: Joi.array().items(Joi.string().min(1).max(100)), AdditionalEmailAttribute1: Joi.string().min(1).max(100).allow('', null), AdditionalEmailAttribute2: Joi.string().min(1).max(100).allow('', null), AdditionalEmailAttribute3: Joi.string().min(1).max(100).allow('', null), AdditionalEmailAttribute4: Joi.string().min(1).max(100).allow('', null), AdditionalEmailAttribute5: Joi.string().min(1).max(100).allow('', null), scheduling_disabled: Joi.strip() };
import { Schema, model, joigoose } from 'config/mongoose' import { setup } from 'helpers/crud' import { leadSource, twilioRecordTypes } from 'helpers/constants' import Joi from 'joi' import _ from 'lodash' const joiSchema = Joi.object({ service: Joi.any().meta({ type: Schema.Types.ObjectId, ref: 'Service' }).required(), market: Joi.any().meta({ type: Schema.Types.ObjectId, ref: 'Market' }).required(), name: Joi.string().required().meta({ index: true }), sendgridGroupId: Joi.number().required(), url: Joi.string(), emailSettings: Joi.object({ from: Joi.string().required(), fromName: Joi.string().required(), domain: Joi.string().required() }), phoneSettings: Joi.object({ inbound: Joi.string().regex(/^[\+0-9]{10,16}$/).required().meta({ index: true }), record: Joi.string().valid(_.values(twilioRecordTypes)) .required().default(twilioRecordTypes.recordFromAnswer), timeLimit: Joi.number().default(1200).required() }),
'use strict'; const Joi = require('joi'); const bcrypt = require('bcrypt'); const Boom = require('boom'); var redisClient = require('redis-connection')(); module.exports.register = { auth: false, validate: { payload: { email: Joi.string().email().required(), password: Joi.string().min(2).max(200).required(), passwordConfirm: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'must match password' } } }) } }, handler: function(request, reply) { redisClient.get(request.payload.email, function (err, redisResp) { if(!redisResp) { // error when if not already registered, register the person: bcrypt.genSalt(12, function(err, salt) { bcrypt.hash(request.payload.password, salt, function(err, hash) { request.payload.password = hash; // save the password's hash redisClient.set(request.payload.email, JSON.stringify(request.payload)); request.cookieAuth.set(data); return reply('Success') }); // end bcrypt.hash }); // end bcrypt.genSalt } else { return reply(Boom.badRequest('Already Registered')); }
'use strict'; const Config = require('ez-config'); const Hoek = require('hoek'); const Boom = require('boom'); const Joi = require('joi'); const Manifest = require('../lib/manifest.js'); const Analytics = require('../lib/analytics.js'); const internals = {}; internals.validation = { optional: Joi.any() .optional(), uri: Joi.string() .uri({ scheme: /https?/ }) .options({ language: { string: { uriCustomScheme: 'must be a valid URI with a http(s) scheme' } } }) .description('URI of the appcache manifest file') }; internals.routeDefaultSettings = { cors: { origin : ['*'], headers : ['X-Requested-With'] }, description: 'Validate appcache manifest', tags: ['api'],
lab.experiment('lout examples', () => { // these are example are taken from https://github.com/hapijs/lout/blob/master/test/routes/default.js /* Copyright (c) 2012-2014, Walmart and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ const routes = [{ method: 'GET', path: '/test', config: { handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().insensitive().required() } }, tags: ['api'], description: 'Test GET', notes: 'test note' } }, { method: 'GET', path: '/another/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().required() } } } }, { method: 'GET', path: '/zanother/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().required() } } } }, { method: 'POST', path: '/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param2: Joi.string().valid('first', 'last'), param3: 'third', param4: 42 } } } }, { method: 'DELETE', path: '/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param2: Joi.string().valid('first', 'last') } } } }, { method: 'PUT', path: '/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param2: Joi.string().valid('first', 'last') } } } }, { method: 'PATCH', path: '/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param2: Joi.string().valid('first', 'last'), param3: Joi.number().valid(42) } } } }, { method: 'GET', path: '/notincluded', config: { tags: ['api'], handler: Helper.defaultHandler, plugins: { lout: false } } }, { method: 'GET', path: '/nested', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object({ nestedparam1: Joi.string().required(), array: Joi.array() }) } } } }, { method: 'GET', path: '/rootobject', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: Joi.object({ param1: Joi.string().required() }) } } }, { method: 'GET', path: '/rootarray', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: Joi.array().items( Joi.string().required(), Joi.object({ param1: Joi.number() }), Joi.number().forbidden() ).min(2).max(5).length(3) } } }, { method: 'GET', path: '/complexarray', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: Joi.array() .ordered('foo', 'bar') .items( Joi.string().required(), Joi.string().valid('four').forbidden(), Joi.object({ param1: Joi.number() }), Joi.number().forbidden() ).min(2).max(5).length(3) .ordered('bar', 'bar') .items( Joi.number().required() ) } } }, { method: 'GET', path: '/path/{pparam}/test', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { params: { pparam: Joi.string().required() } } } }, { method: 'GET', path: '/emptyobject', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object() } } } }, { method: 'GET', path: '/alternatives', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.alternatives().try(Joi.number().required(), Joi.string().valid('first', 'last')) } } } }, { method: 'GET', path: '/withnestedalternatives', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object({ param2: Joi.alternatives().try( { param3: Joi.object({ param4: Joi.number().example(5) }).description('this is cool too') }, Joi.number().min(42) ) }).description('something really cool'), param2: Joi.array().items( Joi.object({ param2: Joi.alternatives().try( { param3: Joi.object({ param4: Joi.number().example(5) }).description('this is cool too') }, Joi.array().items('foo', 'bar'), Joi.number().min(42).required(), Joi.number().max(42).required() ) }).description('all the way down') ).description('something really cool') } } } }, { method: 'GET', path: '/novalidation', config: { tags: ['api'], handler: Helper.defaultHandler } }, { method: 'GET', path: '/withresponse', config: { tags: ['api'], handler: Helper.defaultHandler, response: { schema: { param1: Joi.string() } } } }, { method: 'GET', path: '/withstatus', config: { tags: ['api'], handler: Helper.defaultHandler, response: { schema: { param1: Joi.string() }, status: { 204: { param2: Joi.string() }, 404: { error: 'Failure' } } } } }, { method: 'GET', path: '/withpojoinarray', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.array().items({ param2: Joi.string() }) } } } }, { method: 'POST', path: '/withnestedrulesarray', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { payload: { param1: Joi.array().items(Joi.object({ param2: Joi.array().items(Joi.object({ param3: Joi.string() })).optional() })) } } } }, { method: 'GET', path: '/withhtmlnote', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().notes('<span class="htmltypenote">HTML type note</span>') } }, notes: '<span class="htmlroutenote">HTML route note</span>' } }, { method: 'GET', path: '/withnotesarray', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().notes([ '<span class="htmltypenote">HTML type note</span>', '<span class="htmltypenote">HTML type note</span>' ]) } } } }, { method: 'GET', path: '/withexample', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().regex(/^\w{1,5}$/).example('abcde') } } } }, { method: 'POST', path: '/denybody', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { payload: false } } }, { method: 'POST', path: '/rootemptyobject', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { payload: Joi.object() } } }, { method: 'GET', path: '/withnestedexamples', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object({ param2: Joi.object({ param3: Joi.number().example(5) }).example({ param3: 5 }) }).example({ param2: { param3: 5 } }) } } } }, { method: 'GET', path: '/withmeta', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string().meta({ index: true, unique: true }) } } } }, { method: 'GET', path: '/withunit', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.number().unit('ms') } } } }, { method: 'GET', path: '/withdefaultvalue', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.number().default(42) } } } }, { method: 'GET', path: '/withbinaryencoding', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.binary().min(42).max(128).length(64).encoding('base64') } } } }, { method: 'GET', path: '/withdate', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.date().min('1-1-1974').max('12-31-2020') } } } }, { method: 'GET', path: '/withpeersconditions', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object() .and('a', 'b', 'c') .or('a', 'b', 'c') .xor('a', 'b', 'c') .with('a', ['b', 'c']) .without('a', ['b', 'c']) } } } }, { method: 'GET', path: '/withpattern', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object({ a: Joi.string() }).pattern(/\w\d/, Joi.boolean()) } } } }, { method: 'GET', path: '/withallowunknown', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object().unknown(), param2: Joi.object().unknown(false) } } } }, { method: 'GET', path: '/withstringspecifics', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.string() .alphanum() .regex(/\d{3}.*/) .token() .email() .guid() .isoDate() .hostname() .lowercase() .uppercase() .trim(), param2: Joi.string().email() } } } }, { method: 'GET', path: '/withconditionalalternatives', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.alternatives() .when('b', { is: 5, then: Joi.string(), otherwise: Joi.number().required().description('Things and stuff') }) .when('a', { is: true, then: Joi.date(), otherwise: Joi.any() }), param2: Joi.alternatives() .when('b', { is: 5, then: Joi.string() }) .when('a', { is: true, otherwise: Joi.any() }) } } } }, { method: 'GET', path: '/withreferences', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.ref('a.b'), param2: Joi.ref('$x') } } } }, { method: 'GET', path: '/withassert', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.object().assert('d.e', Joi.ref('a.c'), 'equal to a.c'), param2: Joi.object().assert('$x', Joi.ref('b.e'), 'equal to b.e') } } } }, { method: 'GET', path: '/withproperties', vhost: 'john.doe', config: { tags: ['api'], handler: Helper.defaultHandler, cors: { maxAge: 12345 }, jsonp: 'callback' } }, { method: 'OPTIONS', path: '/optionstest', handler: Helper.defaultHandler }, { method: 'GET', path: '/withrulereference', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.date().min(Joi.ref('param2')), param2: Joi.date() } } } }, { method: 'GET', path: '/withcorstrue', vhost: 'john.doe', config: { tags: ['api'], handler: Helper.defaultHandler, cors: true } }, { method: 'GET', path: '/withstrip', config: { tags: ['api'], handler: Helper.defaultHandler, validate: { query: { param1: Joi.any().strip(), param2: Joi.any() } } } }, { method: 'GET', path: '/internal', config: { tags: ['api'], isInternal: true, handler: Helper.defaultHandler } }]; lab.test('all routes parsed', (done) => { Helper.createServer({}, routes, (err, server) => { expect(err).to.equal(null); server.inject({ method: 'GET', url: '/swagger.json' }, function (response) { //console.log(JSON.stringify(response.result)); expect(response.statusCode).to.equal(200); // the 40 to 45 difference is in one route having a number of methods expect(response.result.paths).to.have.length(40); done(); }); }); }); });
"use strict"; const Joi = require('joi'); const _ = require('lodash'); const commonValidation = require('../../common/validation/common.validation'); const addressValidation = require('../../common/validation/address.validation'); let createPayload = { _id: Joi.string().alphanum().required().min(2), firstName: Joi.string().required(), lastName: Joi.string().required(), middleName: Joi.string().empty('').optional(), password: Joi.string().required(), email: Joi.string().email().required(), contactNumber: Joi.string().required(), dob: Joi.date().optional(), userGroup: Joi.string().required(), gender: Joi.any().tags(['male', 'female', 'other']), isLocked: Joi.boolean().optional(), isActive: Joi.boolean().optional(), address: Joi.object().keys(addressValidation), profilePicToken: Joi.string().empty().optional(), available: Joi.object().keys({ store: Joi.object().keys({ name: Joi.string().required(), availableToChildren: Joi.boolean().optional() }).required() }).required() }; let updatePayload = _.clone(createPayload); delete updatePayload._id; let changePasswordValidation = { password: Joi.string().required()
var createActivity = module.exports.createActivity = function(course, user, type, objectId, objectType, metadata, actor, callback) { metadata = metadata || {}; // Parameter validation var validationSchema = Joi.object().keys({ 'type': Joi.any().valid(_.map(ActivitiesDefaults, 'type')).required(), 'objectId': Joi.number().required(), 'objectType': Joi.any().valid(_.values(CollabosphereConstants.ACTIVITY.OBJECT_TYPES)).required(), 'metadata': Joi.object().optional() }); var validationResult = Joi.validate({ 'type': type, 'objectId': objectId, 'objectType': objectType, 'metadata': metadata }, validationSchema); if (validationResult.error) { return callback({'code': 400, 'msg': validationResult.error.details[0].message}); } // Create the activity in the DB var activity = { 'course_id': course.id, 'user_id': user.id, 'type': type, 'object_type': objectType }; if (metadata) { activity.metadata = metadata; } if (objectType === 'asset') { activity.asset_id = objectId; } else { activity.object_id = objectId; if (metadata.assetId) { activity.asset_id = metadata.assetId; delete metadata.assetId; } } if (actor) { activity.actor_id = actor.id; } // TODO: Wrap this in a transaction DB.Activity.create(activity).complete(function(err, activity) { if (err) { log.error({'err': err}, 'Failed to create a new activity'); return callback({'code': 500, 'msg': err.message}); } // Retrieve the number of points that should be earned for // the current activity in the current course getActivityTypeConfiguration(course.id, function(err, configuration) { if (err) { return callback(err); } // Update the timestamp at which the last activity took place for the user setUserLastActivity(user, actor, function(err) { if (err) { return callback(err); } // Get the activity configuration for this type of activity. If it's been disabled, // we don't have to hand out points var activityConfiguration = _.find(configuration, {'type': type}); if (!activityConfiguration.enabled) { return callback(null, activity); } // Increase the points of the user var points = activityConfiguration.points; user.increment('points', {'by': points}).complete(function(err) { if (err) { log.error({'err': err}, 'Failed to increment the points for a user'); return callback({'code': 500, 'msg': err.message}); } return callback(null, activity); }); }); }); }); };
const isAutomatedBuildStatus = Joi.string().valid('automated', 'manual'); const isBuildStatus = Joi.string().regex(/^(passing|failing|building)$/); const colorsB = mapValues(colorscheme, 'colorB'); const t = new ServiceTester({ id: 'docker', title: 'Docker Hub' }); module.exports = t; // stars endpoint t.create('docker stars (valid, library)') .get('/stars/_/ubuntu.json?style=_shields_test') .expectJSONTypes(Joi.object().keys({ name: 'docker stars', value: isMetric, colorB: Joi.any().equal('#066da5').required() })); t.create('docker stars (override colorB)') .get('/stars/_/ubuntu.json?colorB=fedcba&style=_shields_test') .expectJSONTypes(Joi.object().keys({ name: 'docker stars', value: isMetric, colorB: Joi.any().equal('#fedcba').required() })); t.create('docker stars (valid, user)') .get('/stars/jrottenberg/ffmpeg.json') .expectJSONTypes(Joi.object().keys({ name: 'docker stars', value: isMetric
async function handleRequest(request) { const { key } = request.params; const { value } = request.payload; const uiSettings = request.getUiSettingsService(); await uiSettings.set(key, value); return { settings: await uiSettings.getUserProvided() }; } export const setRoute = { path: '/api/kibana/settings/{key}', method: 'POST', config: { validate: { params: Joi.object().keys({ key: Joi.string().required(), }).default(), payload: Joi.object().keys({ value: Joi.any().required() }).required() }, handler(request) { return handleRequest(request); } } };