Skip to content

Commit

Permalink
add validation function
Browse files Browse the repository at this point in the history
  • Loading branch information
jchris committed Aug 1, 2010
1 parent 97e169d commit 72d7f7b
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
29 changes: 29 additions & 0 deletions validate_doc_update.js
@@ -0,0 +1,29 @@
function (newDoc, oldDoc, userCtx, secObj) {
var v = require("vendor/couchapp/lib/validate").init(newDoc, oldDoc, userCtx, secObj);

if (v.isAdmin()) {
return true; // admin can do anything
}

if (!userCtx.name) {
// this could be configurable based on secObj
v.unauthorized("please login to make changes");
}

// only admin may delete
if (newDoc._deleted) {
v.unauthorized("only admin may delete docs");
}

// attached versions must be preserved
if (oldDoc && oldDoc._attachments) {
for (var n in oldDoc._attachments) {
if (n.indexOf("rev") == 0) {
if (!(newDoc._attachments && newDoc._attachments[n]
&& newDoc._attachments[n].stub === true)) {
v.forbidden("old versions may not be deleted")
}
}
}
}
}
53 changes: 53 additions & 0 deletions vendor/couchapp/lib/validate.js
@@ -0,0 +1,53 @@
// a library for validations
// over time we expect to extract more helpers and move them here.
exports.init = function(newDoc, oldDoc, userCtx, secObj) {
var v = {};

v.forbidden = function(message) {
throw({forbidden : message});
};

v.unauthorized = function(message) {
throw({unauthorized : message});
};

v.assert = function(should, message) {
if (!should) v.forbidden(message);
}

v.isAdmin = function() {
return userCtx.roles.indexOf('_admin') != -1
};

v.isRole = function(role) {
return userCtx.roles.indexOf(role) != -1
};

v.require = function() {
for (var i=0; i < arguments.length; i++) {
var field = arguments[i];
message = "The '"+field+"' field is required.";
if (typeof newDoc[field] == "undefined") v.forbidden(message);
};
};

v.unchanged = function(field) {
if (oldDoc && oldDoc[field] != newDoc[field])
v.forbidden("You may not change the '"+field+"' field.");
};

v.matches = function(field, regex, message) {
if (!newDoc[field].match(regex)) {
message = message || "Format of '"+field+"' field is invalid.";
v.forbidden(message);
}
};

// this ensures that the date will be UTC, parseable, and collate correctly
v.dateFormat = function(field) {
message = "Sorry, '"+field+"' is not a valid date format. Try: 2010-02-24T17:00:03.432Z";
v.matches(field, /\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}(\.\d*)?Z/, message);
}

return v;
};

0 comments on commit 72d7f7b

Please sign in to comment.