Thursday, November 11, 2021

Automate User Creation in Google Workspace


This tutorial demonstrates how to automate the user creation process in Google workspace using Admin SDK.

Step 1: Log in to Google Drive using your Google Workspace account and create a new Google Sheet.

Step 2: Go to Insert > Form and create a new Google Form.

Step 3: Add the desired fields: First Name, Last Name, Recovery Email, Recovery Phone, Reporting Manager, Location, Title, Department, etc.

Step 4: Go to Tools > Script editor.

Step 5: In Apps Script > Go to Project Settings > Check the box for "Show "appsscript.json" manifest file in editor" option.

Step 6: Go to Editor > appsscript.json and change it to the following:

{
"timeZone": "America/New_York",
"dependencies": {
"enabledAdvancedServices": [
{
"userSymbol": "AdminDirectory",
"serviceId": "admin",
"version": "directory_v1"
}
]
},
"exceptionLogging": "STACKDRIVER",
"oauthScopes": [
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/groups",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/script.scriptapp",
"https://www.googleapis.com/auth/script.send_mail",
"https://www.googleapis.com/auth/spreadsheets.currentonly",
"https://apps-apis.google.com/a/feeds/groups/",
"https://www.googleapis.com/auth/admin.directory.group",
"https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/admin.directory.group.member"
],
"runtimeVersion": "V8"
}

Step 7: Go to Editor > Code.gs and change it to the following:

var ADDED_TO_SUBJECT = 'Added to group';
var ADDED_TO_DOC_URL = 'https://docs.google.com/document/d/edit?usp=sharing';

/**
* Installs a trigger on the Spreadsheet when a Form response is submitted.
*/
function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}

/**
* Sends a customized email for every response in a form.
*
* @param {Object} e - Form submit event.
*/
function onFormSubmit(e) {
var responses = e.namedValues;

// If the question title is a label, it can be accessed as an object field.
// If it has spaces or other characters, it can be accessed as a dictionary.
var timestamp = responses.Timestamp[0];
var userEmail = responses['Recovery Email'][0].trim();
var firstName = responses['First Name'][0].trim();
var lastName = responses['Last Name'][0].trim();
var reportingManager = responses['Reporting Manager'][0].trim();
var password = 'randomSecurePassword@1';
var groupEmail = 'group@domain.com'

// Check if the group contains the user's email.
var status = '';
var group = GroupsApp.getGroupByEmail(groupEmail);
if (group.hasUser(userEmail)) {
// User is already in group, send a confirmation email.
status = 'Already in group';
} else {
// User is not part of the group, add user to group.
var user = {
primaryEmail: firstName + '.' + lastName + '@domain.com',
name: {
givenName: firstName,
familyName: lastName,
fullName: firstName + ' ' + lastName,
},
relations: [{
value: reportingManager,
type: 'manager',
}],
password: password,
changePasswordAtNextLogin: 'true',
};

user = AdminDirectory.Users.insert(user);
Logger.log('User %s created with ID %s.', user.primaryEmail, user.id);

// User is not part of the group, add user to group.
var member = {email: firstName + '.' + lastName +
'@domain.com', role: 'MEMBER'};
AdminDirectory.Members.insert(member, groupEmail);

// Send a confirmation email that the member was now added.
var addedToGroupDocId = DocumentApp.openByUrl(ADDED_TO_DOC_URL).getId();

var emailBody = docToHtml(addedToGroupDocId);
emailBody = emailBody.replace('{{EMAIL}}', userEmail);
emailBody = emailBody.replace('{{GOOGLE_GROUP}}', groupEmail);
MailApp.sendEmail({
to: userEmail,
subject: ADDED_TO_SUBJECT,
htmlBody: emailBody,
});
status = 'Newly added';
}

// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = e.range.getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);

Logger.log('status=' + status + '; responses=' +
JSON.stringify(responses));
}

/**
* Fetches a Google Doc as an HTML string.
*
* @param {string} docId - The ID of a Google Doc to fetch content from.
* @return {string} The Google Doc rendered as an HTML string.
*/
function docToHtml(docId) {
var url = 'https://docs.google.com/feeds/download/documents/
export/Export?id=' +
docId + '&exportFormat=html';
var param = {
method: 'get',
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}

Step 8: Go to Services > Add Admin SDK.

Step 9: Select installTrigger function from the dropdown and click on the Run button. (Just do it once; if you run it multiple times, it will create duplicate triggers. You can go to the Triggers menu to delete redundant ones.)


References:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.