Skip to content

Instantly share code, notes, and snippets.

@peteruithoven
Created May 12, 2017 15:41
Show Gist options
  • Save peteruithoven/b8fd1f60ae526c849479e50a38709590 to your computer and use it in GitHub Desktop.
Save peteruithoven/b8fd1f60ae526c849479e50a38709590 to your computer and use it in GitHub Desktop.
Superlogin util to update databases according to configuration
const SuperLogin = require('superlogin');
const superloginConfig = require('../superlogin.config.js');
const DBAuth = require('superlogin/lib/dbauth');
const superlogin = new SuperLogin(superloginConfig);
const { config, userDB } = superlogin;
const dbAuth = new DBAuth(config);
if (!config.getItem('userDBs.defaultDBs')) {
console.log('no userDBs.defaultDBs defined');
process.exit(1);
}
// retrieve all databases configs
let allDBs = [];
function addDBs(dbs, type) {
if (!Array.isArray(dbs)) return;
dbs.forEach(dbName => {
const dbConfig = dbAuth.getDBConfig(dbName);
dbConfig.type = type; // override type
allDBs.push(dbConfig);
});
}
addDBs(config.getItem('userDBs.defaultDBs.private'), 'private');
addDBs(config.getItem('userDBs.defaultDBs.shared'), 'shared');
function getAllUserDocs() {
return userDB.allDocs({ include_docs: true })
.then(({ rows }) => (
rows
.filter(({ id }) => id !== '_design/auth')
.map(row => row.doc)
));
}
function updateDB(userDoc, dbConfig) {
console.log('dbConfig: ', dbConfig);
const { name, designDocs, type, permissions, adminRoles, memberRoles } = dbConfig;
// Add user db:
// get actual db name (depends on private / shared)
// create db's when needed
// update design docs
// get current sessions from userDoc
// Update _security doc of db with updated session with new permissions
return dbAuth.addUserDB(
userDoc,
name,
designDocs,
type,
permissions,
adminRoles,
memberRoles
);
}
// get user docs
getAllUserDocs()
.then(userDocs => {
const userUpdates = [];
// go through users
return asyncIterator(userDocs, userDoc => {
// go through databases
return asyncIterator(allDBs, dbConfig => {
// update database
return updateDB(userDoc, dbConfig)
.then(finalDBName => {
// update userDoc's personalDBs
userDoc.personalDBs[finalDBName] = {
name: dbConfig.name,
type: dbConfig.type
};
userUpdates.push(userDoc);
});
});
})
// Bulk save user doc updates
.then(() => userDB.bulkDocs(userUpdates));
})
.then(() => process.exit());
function asyncIterator(args, callback) {
return new Promise((resolve, reject) => {
const results = [];
if (args.length === 0) resolve(results);
const clone = [...args];
function loop(arg) {
callback(arg).then(function (result) {
results.push(result);
if (clone.length > 0) {
loop(clone.shift());
} else {
resolve(results);
}
});
}
loop(clone.shift());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment