Skip to content

Instantly share code, notes, and snippets.

@indolering
Last active August 29, 2015 14:01
Show Gist options
  • Save indolering/c7b27828088a16f0717a to your computer and use it in GitHub Desktop.
Save indolering/c7b27828088a16f0717a to your computer and use it in GitHub Desktop.
'use strict';
function map(doc,emit,rejectify) {
var that = this;
this.regexes = {
good: (/^[a-z0-9][a-z0-9.-:]{2}[a-z0-9_.!~*'()#;,?:-@&=+$]|\/*/),
bad: (/^(0|10|127|192|198|24[0-5]|255).*|^localhost.*|^(::$|::1$|2001:db8:.*)|^\s.*/),
name: (/^[a-z]$|^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/)
};
/*
* This is a rather convoluted piece of logic due to trying to operate in 3 environments:
* if( doc -> Are you running as part of a Mapper = require('mapper') // map = new Mapper.map() statement?
* && !doc.error -> Did nmc2couch.js find an error while trying to parse record PRIOR to adding it to CouchDB?
* && doc.namespace -> Are you part of the 'd' namespace?
* && that.validName(doc.name) -> is your name valid for this namespace?
*
* else if(reject) are you being called as part of a unit test?
* */
if (doc && !doc.error && doc.namespace === 'd' && that.validName(doc.name)) {
var entry = that.validEntry(doc.value);
if (entry !== false) {
emit(doc.name, {"http": entry});
} else if(rejectify){ //are you being called as part of a unit test NOT in CouchDB?
rejectify(false);
}
}
this.validName = function (name) { //covered
return that.regexes.name.test(name);
};
this.checkValue = function (value) { //covered
return that.regexes.good.test(value) && !that.regexes.bad.test(value) && !that.squatter(value);
};
this.squatter = function (value) { //covered
return sString(value) || sRegex(value);
function sString(value) {
var squatters = [
"91.250.85.116",
"73.239.23.14",
"212.232.51.96"
];
return squatters.some(function (squatter) {
return value.indexOf(squatter) > -1;
});
}
function sRegex(value) {
var regexes = [
(/^[a-z0-9_.!~*'()#-;,?@&=+$]*@.*/), //email check
(/^BM-.*/)
];
return regexes.some(function (regex) {
return regex.test(value);
});
}
};
this.validEntry = function (entry) {
var transports = ['http', 'translate', 'map', 'ip'];
transports.forEach(function (transport) {
try { //protects against non-existent records ... not sure if needed.
var checkedValue = false;
if (entry.hasOwnProperty(transport)) {
switch (transport) {
case "http":
case "ip":
checkedValue = entry[transport];
break;
case "translate":
checkedValue = entry[transport];
if (checkedValue.charAt(-1) === '.') { //remove FQDN period
checkedValue = checkedValue.slice(0, -1);
}
break;
case "map":
if (entry.map.hasOwnProperty("")) {
checkedValue = entry.map[""];
}
break;
}
if(checkedValue !== false && checkValue(checkedValue)){
return checkedValue;
}
}
} catch (e) {
console.log(e);
}
});
return false;
};
}
module.exports.map = map;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment