Skip to content

Instantly share code, notes, and snippets.

@erikbern

erikbern/group-rotation.js

Last active Oct 20, 2016
Embed
What would you like to do?
Update a Google group to contain only one single member
/*
This code is meant to be used with a rotating responsibility for incoming bugs and stuff.
To make this work, you need to:
1. Set up the key in the Google IAM manager
2. Add domain delegation for the user
3. Download the key and add the following fields: "admin_email" and "domain"
*/
var key = require('./google-people-api-creds.json');
var scope = ['https://www.googleapis.com/auth/admin.directory.group',
'https://www.googleapis.com/auth/admin.directory.group.member',
'https://www.googleapis.com/auth/admin.directory.user'];
var bluebird = require('bluebird');
var google = require('googleapis');
function updateGroup(groupName, userName) {
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, scope, key.admin_email);
bluebird.promisifyAll(jwtClient);
var client;
var userKey, groupKey;
return jwtClient.authorizeAsync()
.then(function() {
client = google.admin('directory_v1');
bluebird.promisifyAll(client.users);
bluebird.promisifyAll(client.groups);
bluebird.promisifyAll(client.members);
return client.members.listAsync({
auth: jwtClient,
groupKey: groupName + '@' + key.domain
}).then(function(res) {
// Delete all members
return bluebird.all(res.members
.filter(function(m) { return m.email != 'admin@' + key.domain; })
.map(function(m) {
console.log('Deleting user ' + m.email);
return client.members.deleteAsync({
auth: jwtClient,
groupKey: groupName + '@' + key.domain,
memberKey: m.email
});
}));
}).then(function(res) {
console.log('Deleted all users!');
console.log('Adding user ' + userName);
return client.members.insertAsync({
auth: jwtClient,
groupKey: groupName + '@' + key.domain,
resource: {
email: userName + '@' + key.domain
}
});
});
});
}
updateGroup('dev-goalie-rotation', 'selberg');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment