Database / CouchDB Interview Questions
How do you implement document-level security in CouchDB using validate_doc_update functions?
The validate_doc_update (VDU) function is a JavaScript function stored in a design document that CouchDB calls before every document write to that database. If the function throws an error, the write is rejected with the specified HTTP status and message. This is the primary mechanism for enforcing document-level business rules and security policies.
// In _design/security:
{
"validate_doc_update": "function(newDoc, oldDoc, userCtx, secObj) {
// Reject if not logged in
if (!userCtx.name) {
throw({ unauthorized: 'You must be logged in to write documents.' });
}
// Enforce required fields
if (!newDoc.type) {
throw({ forbidden: 'Documents must have a type field.' });
}
// Prevent changing the owner field after creation
if (oldDoc && oldDoc.owner !== newDoc.owner) {
throw({ forbidden: 'Cannot change document owner.' });
}
// Only admins can set status to archived
if (newDoc.status === 'archived' && userCtx.roles.indexOf('_admin') === -1) {
throw({ forbidden: 'Only admins can archive documents.' });
}
}"
}
The function receives four arguments:
newDoc— the document being written (the new version).oldDoc— the existing document (null if this is a new document creation).userCtx— the user context:{ name, roles, db }. Roles include_adminfor server admins and_reader,_writer, or custom roles from the user's profile.secObj— the database's_securityobject.
Throw { unauthorized: "message" } to return HTTP 401 (authentication required). Throw { forbidden: "message" } to return HTTP 403 (permission denied). Any other JavaScript throw returns HTTP 500.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
