Join our webinar on Wednesday, June 26, at 1pm EDTHow Chia Mitigates Risk in the Crypto Industry.Register
Socket
Socket
Sign inDemoInstall

swagger-tools

Package Overview
Dependencies
5
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.4.8 to 0.5.0

34

index.js
/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -16,0 +24,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -239,5 +247,3 @@

module.exports = {
v1_2: new Specification('1.2'), // jshint ignore:line
v2_0: new Specification('2.0') // jshint ignore:line
};
module.exports.v1 = module.exports.v1_2 = new Specification('1.2'); // jshint ignore:line
module.exports.v2 = module.exports.v2_0 = new Specification('2.0'); // jshint ignore:line
/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -16,0 +24,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -16,0 +24,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -22,98 +30,2 @@

// http://tools.ietf.org/html/rfc3339#section-5.6
var dateRegExp = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTimeRegExp = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/;
var isValid = function isValid (val, type, format) {
var isValidDate = function isValidDate (date) {
var day;
var matches;
var month;
if (!_.isString(date)) {
date = date.toString();
}
matches = dateRegExp.exec(date);
if (matches === null) {
return false;
}
day = matches[3];
month = matches[2];
if (month < '01' || month > '12' || day < '01' || day > '31') {
return false;
}
return true;
};
var isValidDateTime = function isValidDateTime (dateTime) {
var hour;
var date;
var time;
var matches;
var minute;
var parts;
var second;
if (!_.isString(dateTime)) {
dateTime = dateTime.toString();
}
parts = dateTime.toLowerCase().split('t');
date = parts[0];
time = parts.length > 1 ? parts[1] : undefined;
if (!isValidDate(date)) {
return false;
}
matches = dateTimeRegExp.exec(time);
if (matches === null) {
return false;
}
hour = matches[1];
minute = matches[2];
second = matches[3];
if (hour > '23' || minute > '59' || second > '59') {
return false;
}
return true;
};
var result = true;
switch (type) {
case 'boolean':
result = _.isBoolean(val) || ['false', 'true'].indexOf(val) !== -1;
break;
case 'integer':
result = !_.isNaN(parseInt(val, 10));
break;
case 'number':
result = !_.isNaN(parseFloat(val));
break;
case 'string':
if (!_.isUndefined(format)) {
switch (format) {
case 'date':
result = isValidDate(val);
break;
case 'date-time':
result = isValidDateTime(val);
break;
}
}
break;
}
return result;
};
/**

@@ -129,2 +41,4 @@ * Middleware for using Swagger information to validate API requests prior to sending the request to the route handler.

// TODO: Add support for validating models (https://github.com/apigee-127/swagger-tools/issues/18)
return function swaggerValidator (req, res, next) {

@@ -140,11 +54,7 @@ var operation = req.swagger ? req.swagger.operation : undefined;

_.each(operation.parameters || [], function (param) {
var minimum = param.minimum;
var maximum = param.maximum;
var invalidParamPrefix = 'Parameter (' + param.name + ') ';
var invalidTypePrefix = invalidParamPrefix + 'is not a valid ';
var testVal;
var val = req.swagger.params[param.name].value;
var paramName = param.name;
var val = req.swagger.params[paramName].value;
// Validate requiredness
validators.validateRequiredness(param.name, val, param.required);
validators.validateRequiredness(paramName, val, param.required);

@@ -157,62 +67,19 @@ // Quick return if the value is not present

// Validate the value type/format
if (!isValid(val, param.type, param.format)) {
throw new Error(invalidTypePrefix + (_.isUndefined(param.format) ? '' : param.format + ' ') +
param.type + ': ' + val);
}
validators.validateTypeAndFormat(paramName, val,
param.type === 'array' ? param.items.type : param.type,
param.type === 'array' && param.items.format ?
param.items.format :
param.format);
if (param.type === 'integer') {
testVal = parseInt(val, 10);
} else if (param.type === 'number') {
testVal = parseFloat(val);
}
// Validate enum
if (!_.isUndefined(param.enum) && param.enum.indexOf(val) === -1) {
throw new Error(invalidParamPrefix + 'is not an allowable value (' + param.enum.join(', ') + '): ' + val);
}
validators.validateEnum(paramName, val, param.enum);
// Validate maximum
if (!_.isUndefined(maximum)) {
if (!_.isNumber(maximum)) {
maximum = parseFloat(maximum);
}
validators.validateMaximum(paramName, val, param.maximum, param.type);
if (testVal > maximum) {
throw new Error(invalidParamPrefix + 'is greater than the configured maximum (' + param.maximum +
'): ' + val);
}
}
// Validate minimum
if (!_.isUndefined(minimum)) {
if (!_.isNumber(minimum)) {
minimum = parseFloat(minimum);
}
validators.validateMinimum(paramName, val, param.minimum, param.type);
if (testVal < minimum) {
throw new Error(invalidParamPrefix + 'is less than the configured minimum (' + param.minimum + '): ' +
val);
}
}
// Validate array
if (param.type === 'array') {
try {
val.forEach(function (aVal, index) {
if (!isValid(aVal, param.items.type, param.format)) {
throw Error(invalidParamPrefix + 'at index ' + index + ' is not a valid ' + param.items.type + ': ' +
aVal);
}
});
} catch (err) {
throw new Error(err.message);
}
}
// Validate uniqueItems
if (!_.isUndefined(param.uniqueItems)) {
if (_.uniq(val).length !== val.length) {
throw new Error(invalidParamPrefix + 'does not allow duplicate values: ' + val.join(', '));
}
}
validators.validateUniqueItems(paramName, val, param.uniqueItems);
});

@@ -219,0 +86,0 @@ } catch (err) {

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -133,3 +141,3 @@

if (_.isUndefined(val) && !_.isUndefined(param.schema) && !_.isUndefined(param.schema.default)) {
val = param.default;
val = param.schema.default;
}

@@ -136,0 +144,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -16,0 +24,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -32,2 +40,4 @@

// TODO: Add support for validating models (https://github.com/apigee-127/swagger-tools/issues/18)
return function swaggerValidator (req, res, next) {

@@ -42,7 +52,52 @@ var operation = req.swagger ? req.swagger.operation : undefined;

_.each(_.union(req.path.parameters, operation.parameters), function (param) {
var val = req.swagger.params[param.name].value;
_.each(_.union(req.swagger.path.parameters, operation.parameters), function (param) {
var paramName = param.name;
var val = req.swagger.params[paramName].value;
// Validate requiredness
validators.validateRequiredness(param.name, val, param.required);
validators.validateRequiredness(paramName, val, param.required);
// Quick return if the value is not present
if (_.isUndefined(val)) {
return;
}
// Constraints can appear in the parameter itself (type/format) and in the parameter's schema (if available)
if (param.schema) {
param = param.schema;
}
// Validate the value type/format
validators.validateTypeAndFormat(paramName, val,
param.type === 'array' ? param.items.type : param.type,
param.type === 'array' && param.items.format ?
param.items.format :
param.format);
// Validate enum
validators.validateEnum(paramName, val, param.enum);
// Validate maximum
validators.validateMaximum(paramName, val, param.maximum, param.type, param.exclusiveMaximum);
// Validate maximum items
validators.validateMaxItems(paramName, val, param.maxItems);
// Validate maximum length
validators.validateMaxLength(paramName, val, param.maxLength);
// Validate minimum
validators.validateMinimum(paramName, val, param.minimum, param.type, param.exclusiveMinimum);
// Validate minimum items
validators.validateMinItems(paramName, val, param.minItems);
// Validate minimum length
validators.validateMinLength(paramName, val, param.minLength);
// Validate pattern
validators.validatePattern(paramName, val, param.pattern);
// Validate uniqueItems
validators.validateUniqueItems(paramName, val, param.uniqueItems);
});

@@ -49,0 +104,0 @@ } catch (err) {

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* This module contains common methods used in various middleware(s).
*/
'use strict';

@@ -22,0 +26,0 @@

/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

@@ -19,13 +27,12 @@

module.exports = {
v1_2: { // jshint ignore:line
swaggerMetadata: require('./1.2/swagger-metadata'),
swaggerRouter: require('./1.2/swagger-router'),
swaggerValidator: require('./1.2/swagger-validator')
},
v2_0: { // jshint ignore:line
swaggerMetadata: require('./2.0/swagger-metadata'),
swaggerRouter: require('./2.0/swagger-router'),
// swaggerValidator: require('./2.0/swagger-validator')
}
module.exports.v1 = module.exports.v1_2 = { // jshint ignore:line
swaggerMetadata: require('./1.2/swagger-metadata'),
swaggerRouter: require('./1.2/swagger-router'),
swaggerValidator: require('./1.2/swagger-validator')
};
module.exports.v2 = module.exports.v2_0 = { // jshint ignore:line
swaggerMetadata: require('./2.0/swagger-metadata'),
swaggerRouter: require('./2.0/swagger-router'),
swaggerValidator: require('./2.0/swagger-validator')
};
/*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* This module contains common methods used in request validation.
*/
'use strict';

@@ -25,8 +29,73 @@

// http://tools.ietf.org/html/rfc3339#section-5.6
var dateRegExp = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTimeRegExp = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/;
var throwInvalidParameter = function throwInvalidParameter (name, message) {
throw new Error('Parameter (' + name + ') ' + message);
};
var isValidDate = function isValidDate (date) {
var day;
var matches;
var month;
if (!_.isString(date)) {
date = date.toString();
}
matches = dateRegExp.exec(date);
if (matches === null) {
return false;
}
day = matches[3];
month = matches[2];
if (month < '01' || month > '12' || day < '01' || day > '31') {
return false;
}
return true;
};
var isValidDateTime = function isValidDateTime (dateTime) {
var hour;
var date;
var time;
var matches;
var minute;
var parts;
var second;
if (!_.isString(dateTime)) {
dateTime = dateTime.toString();
}
parts = dateTime.toLowerCase().split('t');
date = parts[0];
time = parts.length > 1 ? parts[1] : undefined;
if (!isValidDate(date)) {
return false;
}
matches = dateTimeRegExp.exec(time);
if (matches === null) {
return false;
}
hour = matches[1];
minute = matches[2];
second = matches[3];
if (hour > '23' || minute > '59' || second > '59') {
return false;
}
return true;
};
/**
* Validates the request's content type.
* Validates the request's content type (when necessary).
*

@@ -44,2 +113,5 @@ * @param {string[]} gConsumes - The valid consumes at the API scope

// Get only the content type
contentType = contentType.split(';')[0];
// Validate content type (Only for POST/PUT per HTTP spec)

@@ -52,6 +124,166 @@ if (consumes.length > 0 && ['POST', 'PUT'].indexOf(req.method) !== -1 && consumes.indexOf(contentType) === -1) {

/**
* Validates the request parameter's requiredness.
* Validates the request parameter's value against the allowable values (when necessary).
*
* @param {string} - The parameter name
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string[]} allowed - The allowable values
*
* @throws Error if the value is not allowable
*/
module.exports.validateEnum = function validateEnum (name, val, allowed) {
if (!_.isUndefined(allowed) && !_.isUndefined(val) && allowed.indexOf(val) === -1) {
throwInvalidParameter(name, 'is not an allowable value (' + allowed.join(', ') + '): ' + val);
}
};
/**
* Validates the request parameter's value is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} maximum - The maximum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the maximum in its comparison
*
* @throws Error if the value is greater than the maximum
*/
module.exports.validateMaximum = function validateMaximum (name, val, maximum, type, exclusive) {
var testMax;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(maximum)) {
testMax = parseFloat(maximum);
if (exclusive && testVal >= testMax) {
throwInvalidParameter(name, 'is greater than or equal to the configured maximum (' + maximum + '): ' + val);
} else if (testVal > testMax) {
throwInvalidParameter(name, 'is greater than the configured maximum (' + maximum + '): ' + val);
}
}
};
/**
* Validates the request parameter's array count is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} maxItems - The maximum number of items
*
* @throws Error if the value contains more items than allowable
*/
module.exports.validateMaxItems = function validateMaxItems (name, val, maxItems) {
if (!_.isUndefined(maxItems) && val.length > maxItems) {
throwInvalidParameter(name, 'contains more items than allowed: ' + maxItems);
}
};
/**
* Validates the request parameter's length is less than the maximum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} maxLength - The maximum length
*
* @throws Error if the value's length is greater than the maximum
*/
module.exports.validateMaxLength = function validateMaxLength (name, val, maxLength) {
if (!_.isUndefined(maxLength) && val.length > maxLength) {
throwInvalidParameter(name, 'is longer than allowed: ' + maxLength);
}
};
/**
* Validates the request parameter's array count is greater than the minimum (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} minimum - The minimum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the minimum in its comparison
*
* @throws Error if the value is less than the minimum
*/
module.exports.validateMinimum = function validateMinimum (name, val, minimum, type, exclusive) {
var testMin;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(minimum)) {
testMin = parseFloat(minimum);
if (exclusive && testVal <= testMin) {
throwInvalidParameter(name, 'is less than or equal to the configured minimum (' + minimum + '): ' + val);
} else if (testVal < testMin) {
throwInvalidParameter(name, 'is less than the configured minimum (' + minimum + '): ' + val);
}
}
};
/**
* Validates the request parameter's value contains fewer items than allowed (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} minItems - The minimum number of items
*
* @throws Error if the value contains fewer items than allowable
*/
module.exports.validateMinItems = function validateMinItems (name, val, minItems) {
if (!_.isUndefined(minItems) && val.length < minItems) {
throwInvalidParameter(name, 'contains fewer items than allowed: ' + minItems);
}
};
/**
* Validates the request parameter's length is greater than the minimum (when necessary).
*
* @param {string} name - The parameter name
* @param {*[]} val - The parameter value
* @param {number} minLength - The minimum length
*
* @throws Error if the value's length is less than the minimum
*/
module.exports.validateMinLength = function validateMinLength (name, val, minLength) {
if (!_.isUndefined(minLength) && val.length < minLength) {
throwInvalidParameter(name, 'is shorter than allowed: ' + minLength);
}
};
/**
* Validates the request parameter's matches a pattern (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} pattern - The pattern
*
* @throws Error if the value does not match the pattern
*/
module.exports.validatePattern = function validatePattern (name, val, pattern) {
if (!_.isUndefined(pattern) && _.isNull(val.match(new RegExp(pattern)))) {
throwInvalidParameter(name, 'does not match required pattern: ' + pattern);
}
};
/**
* Validates the request parameter's requiredness (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {boolean} required - Whether or not the parameter is required

@@ -66,1 +298,69 @@ *

};
/**
* Validates the request parameter's type and format (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} type - The parameter type
* @param {string} format - The parameter format
* @param {boolean} [skipError=false] - Whether or not to skip throwing an error (Useful for validating arrays)
*
* @throws Error if the value is not the proper type or format
*/
module.exports.validateTypeAndFormat = function validateTypeAndFormat (name, val, type, format, skipError) {
var result = true;
if (_.isArray(val)) {
_.each(val, function (aVal, index) {
if (!validateTypeAndFormat(name, aVal, type, format, true)) {
throwInvalidParameter(name, 'at index ' + index + ' is not a valid ' + type + ': ' + aVal);
}
});
} else {
switch (type) {
case 'boolean':
result = _.isBoolean(val) || ['false', 'true'].indexOf(val) !== -1;
break;
case 'integer':
result = !_.isNaN(parseInt(val, 10));
break;
case 'number':
result = !_.isNaN(parseFloat(val));
break;
case 'string':
if (!_.isUndefined(format)) {
switch (format) {
case 'date':
result = isValidDate(val);
break;
case 'date-time':
result = isValidDateTime(val);
break;
}
}
break;
}
}
if (skipError) {
return result;
} else if (!result) {
throwInvalidParameter(name, 'is not a valid ' + (_.isUndefined(format) ? '' : format + ' ') + type + ': ' + val);
}
};
/**
* Validates the request parameter's values are unique (when necessary).
*
* @param {string} name - The parameter name
* @param {string[]} val - The parameter value
* @param {boolean} isUnique - Whether or not the parameter values are unique
*
* @throws Error if the value has duplicates
*/
module.exports.validateUniqueItems = function validateUniqueItems (name, val, isUnique) {
if (!_.isUndefined(isUnique) && _.uniq(val).length !== val.length) {
throwInvalidParameter(name, 'does not allow duplicate values: ' + val.join(', '));
}
};
{
"name": "swagger-tools",
"version": "0.4.8",
"version": "0.5.0",
"description": "Various tools for using and integrating with Swagger.",

@@ -18,8 +18,3 @@ "main": "index.js",

"homepage": "https://github.com/apigee/connect-swagger",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"license": "MIT",
"repository": {

@@ -26,0 +21,0 @@ "type": "git",

@@ -11,2 +11,3 @@ The project provides various tools for integrating and interacting with Swagger. This project is in its infancy but

* Downloads: [![NPM Downloads Per Month](http://img.shields.io/npm/dm/swagger-tools.svg)](https://www.npmjs.org/package/swagger-tools)
* License: [![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/apigee-127/swagger-tools/blob/master/LICENSE)
* Version: [![NPM Version](http://img.shields.io/npm/v/swagger-tools.svg)](https://www.npmjs.org/package/swagger-tools)

@@ -51,15 +52,21 @@

**Swagger 1.2 (v1) Example**
```javascript
var swagger = require('swagger-tools');
// 1.2 Example
var spec1 = swagger.specs.v1_2;
var spec = swagger.specs.v1_2; // Could also use 'swagger.specs.v1'
var petJson = require('./samples/1.2/pet.json');
var rlJson = require('./samples/1.2/resource-listing.json');
var results1 = spec1.validate(rlJson, [petJson]);
var results = spec.validate(rlJson, [petJson]);
```
// 2.0 Example
**Swagger 2.0 (v2) Example**
```javascript
var swagger = require('swagger-tools');
var spec = swagger.specs.v2_0; // Could also use 'swagger.specs.v2'
var petStoreJson = require('./samples/2.0/petstore.json');
var spec2 = swagger.specs.v2_0;
var results2 = spec2.validate(petStoreJson);
var results = spec.validate(petStoreJson);
```

@@ -69,4 +76,7 @@

**Swagger 1.2 (v1) Example**
```javascript
var connect = require('connect');
var swagger = require('swagger-tools');
var petJson = require('./samples/1.2/pet.json');

@@ -76,5 +86,7 @@ var resourceListing = require('./samples/1.2/resource-listing.json');

var userJson = require('./samples/1.2/store.json');
var swaggerMetadata = require('swagger-tools/middleware/swagger-metadata');
var swaggerRouter = require('swagger-tools/middleware/swagger-router');
var swaggerValidator = require('swagger-tools/middleware/swagger-validator');
var swaggerMetadata = swagger.middleware.v1_2.swaggerMetadata; // Could also use 'swagger.metadata.v1.swaggerMetadata'
var swaggerRouter = swagger.middleware.v1_2.swaggerRouter; // Could also use 'swagger.metadata.v1.swaggerRouter'
var swaggerValidator = swagger.middleware.v1_2.swaggerValidator; // Could also use 'swagger.metadata.v1.swaggerValidator'
var connect = require('connect');
var app = connect();

@@ -94,2 +106,27 @@

**Swagger 2.0 (v2) Example**
```javascript
var swagger = require('swagger-tools');
var swaggerObject = require('./samples/2.0/petstore.json');
var swaggerMetadata = swagger.middleware.v2_0.swaggerMetadata; // Could also use 'swagger.metadata.v2.swaggerMetadata'
var swaggerRouter = swagger.middleware.v2_0.swaggerRouter; // Could also use 'swagger.metadata.v2.swaggerRouter'
var swaggerValidator = swagger.middleware.v2_0.swaggerValidator; // Could also use 'swagger.metadata.v2.swaggerValidator'
var connect = require('connect');
var app = connect();
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(swaggerMetadata(swaggerObject));
// Validate Swagger requests
app.use(swaggerValidator());
// Route validated requests to appropriate controller
app.use(swaggerRouter({useStubs: true, controllers: './controllers'}));
// ...
```
## Contributing

@@ -96,0 +133,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc