Skip to content

Commit

Permalink
Merge pull request #5 from doitintl/filter-all-reports
Browse files Browse the repository at this point in the history
Filter all reports
  • Loading branch information
dchristlieb authored Aug 1, 2024
2 parents e05deb5 + 5d86f39 commit e1182b3
Show file tree
Hide file tree
Showing 9 changed files with 144 additions and 75 deletions.
91 changes: 49 additions & 42 deletions getAppPasswords.gs
Original file line number Diff line number Diff line change
Expand Up @@ -6,92 +6,99 @@
function getAppPasswords() {
const userEmail = Session.getActiveUser().getEmail();
const domain = userEmail.split("@").pop();
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheets = spreadsheet.getSheets();
const lastSheetIndex = sheets.length;

// Create or clear the "App Passwords" sheet at the last index
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// Check for existing sheet and handle duplicates
let appPasswordsSheet = spreadsheet.getSheetByName("App Passwords");
if (appPasswordsSheet) {
// If the sheet exists, delete it first
spreadsheet.deleteSheet(appPasswordsSheet);
}
appPasswordsSheet = spreadsheet.insertSheet("App Passwords", lastSheetIndex);

// Set font to Montserrat
appPasswordsSheet.getRange("A1:Z1").setFontFamily("Montserrat");

// Add headers
const headers = ["CodeID", "Name", "Creation Time", "Last Time Used", "User"];
appPasswordsSheet.appendRow(headers);
// Create a new sheet with the desired name
appPasswordsSheet = spreadsheet.insertSheet("App Passwords", spreadsheet.getNumSheets());

// Apply formatting to the header row
const headerRange = appPasswordsSheet.getRange(1, 1, 1, headers.length);
headerRange.setBackground("#fc3165").setFontColor("white").setFontWeight("bold");
// Sheet styling (concise)
const headerRange = appPasswordsSheet.getRange("A1:E1");
headerRange.setFontFamily("Montserrat")
.setBackground("#fc3165")
.setFontColor("white")
.setFontWeight("bold")
.setValues([["CodeID", "Name", "Creation Time", "Last Time Used", "User"]]);

// Freeze the header row
appPasswordsSheet.setFrozenRows(1);

// Delete columns F-Z. deleteColumns is called twice because (6, 20) was not deleting the last column.
appPasswordsSheet.deleteColumns(7, 20);
appPasswordsSheet.deleteColumns(6);

// Set pagination parameters
let pageToken = null;

do {
// Make an API call to retrieve users
const options = {
const response = AdminDirectory.Users.list({
domain: domain,
customer: "my_customer",
maxResults: 100,
projection: "FULL",
viewType: "admin_view",
orderBy: "email",
pageToken: pageToken,
};
});

const response = AdminDirectory.Users.list(options);

// Process the retrieved users
processUsers(response.users, appPasswordsSheet);
if (response.users && response.users.length > 0) {
processUsers(response.users, appPasswordsSheet);
}

// Update the page token for the next iteration
pageToken = response.nextPageToken;
} while (pageToken);

// Auto resize the columns
// Auto-resize and add filter after data is populated
appPasswordsSheet.autoResizeColumns(1, 5);
const lastRow = appPasswordsSheet.getLastRow();
appPasswordsSheet.getRange('B1:E' + lastRow).createFilter();
}

function processUsers(users, sheet) {
// Prepare data array
const data = [];

// Iterate over the retrieved users
users.forEach(function (user) {
// Retrieve app passwords for the user
const asps = AdminDirectory.Asps.list(user.primaryEmail);

// Process app passwords
if (asps && asps.items) {
asps.items.forEach(function (asp) {
data.push([
asp.codeId,
asp.name,
asp.creationTime,
asp.lastTimeUsed,
formatTimestamp(asp.creationTime),
asp.lastTimeUsed ? formatTimestamp(asp.lastTimeUsed) : "",
user.primaryEmail,
]);
});
}
});

// Write the data to the sheet in chunks to reduce API calls
const batchSize = 1000;
// Dynamic batch write:
const batchSize = 500; // Maximum batch size

for (let i = 0; i < data.length; i += batchSize) {
const chunk = data.slice(i, i + batchSize);
if (chunk.length > 0) {
sheet.getRange(sheet.getLastRow() + 1, 1, chunk.length, chunk[0].length).setValues(chunk);
}
const chunk = data.slice(i, i + batchSize); // Get the current chunk of data
const numRows = chunk.length; // Number of rows in the current chunk

// Write only the necessary number of rows
sheet.getRange(sheet.getLastRow() + 1, 1, numRows, chunk[0].length)
.setValues(chunk);
}
}

// Corrected timestamp formatting:
function formatTimestamp(timestampString) {
if (timestampString === "0" || timestampString === 0) {
return "Never Used"; // Handle 0 timestamps
} else if (typeof timestampString === "string" && timestampString.length >= 13) {
const timestamp = parseInt(timestampString.slice(0, 13));
const date = new Date(timestamp);
return Utilities.formatDate(date, Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss");
} else {
Logger.log("Unknown timestamp format: " + timestampString);
return "Invalid Timestamp";
}
}




17 changes: 16 additions & 1 deletion getDomainsDNS.gs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,21 @@ sheet.getRange('A2').setValue('google.com');

const rules = [ruleD, ruleE, ruleF, ruleG, ruleDRed, ruleERed, ruleFRed, ruleGRed];
sheet.setConditionalFormatRules(rules);

// --- Add Persistent Toast Notification ---
SpreadsheetApp.getActiveSpreadsheet().toast(
"If you use a third-party mail relay or a SPF flattener, records may be highlighted red and should be manually inspected.",
"Instructions",
-1 // Persistent toast
);

// --- Add Filter View ---
// --- Add Filter View ---
const filterRange = sheet.getRange('B1:G' + lastRow); // Define the filter range
filterRange.createFilter();

// --- Freeze Row 1 ---
sheet.setFrozenRows(1);
}

function NSLookup(type, domain) { //Function takes DNS record type and domain as input
Expand Down Expand Up @@ -219,4 +234,4 @@ function NSLookup(type, domain) { //Function takes DNS record type and domain as
const outputString = outputData.join('\n');

return outputString;
}
}
22 changes: 15 additions & 7 deletions getGroupMembers.gs
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,24 @@ function getGroupMembers() {

// Set up the sheet with headers and formatting
groupMembersSheet.getRange("A1:F1").setValues([["Group Email", "Member Email", "Member Role", "Member Status", "Member Type", "Member ID"]]);
groupMembersSheet.getRange("A1:F1").setFontColor("#ffffff").setFontSize(10).setFontFamily("Montserrat").setBackground("#fc3165").setFontWeight("bold");
groupMembersSheet.setFrozenRows(1);
// Delete columns G-Z
groupMembersSheet.deleteColumns(7, 20);
groupMembersSheet.getRange("A1:F1").setFontColor("#ffffff").setFontSize(10).setFontFamily("Montserrat").setBackground("#fc3165").setFontWeight ("bold");
groupMembersSheet.setFrozenRows(1);

// Append data to the end of the sheet
// --- Add Note to Cell D1 ---
groupMembersSheet.getRange("D1").setNote("A yellow highlighted row indicates a group member from an external organization.");

// --- Add Filter View ---
const lastRow = groupMembersSheet.getLastRow();
groupMembersSheet.getRange(lastRow + 1, 1, groupMembers.length, groupMembers[0].length).setValues(groupMembers);
const filterRange = groupMembersSheet.getRange('A1:F' + lastRow); // Filter columns A through F, starting from row 1
filterRange.createFilter();

// Append data to the end of the sheet (starting from row 3)
groupMembersSheet.getRange(lastRow + 1, 1, groupMembers.length, groupMembers[0].length).setValues(groupMembers);
groupMembersSheet.autoResizeColumns(1, 6);

// Delete columns G-Z (starting from row 3)
groupMembersSheet.deleteColumns(7, 20); // G to Z

// Apply conditional formatting
const range = groupMembersSheet.getRange("D2:D" + (lastRow + groupMembers.length));
const rules = [
Expand Down Expand Up @@ -123,4 +131,4 @@ function getGroupMembers() {
`Error writing group members to spreadsheet: ${error.message}`,
);
}
}
}
7 changes: 7 additions & 0 deletions getGroupSettings.gs
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,13 @@ groupSettingsSheet.setConditionalFormatRules(rules);
}
pageToken = page.nextPageToken;
} while (pageToken);

// --- Add Filter View ---
const lastRow = groupSettingsSheet.getLastRow();
// Filter columns C through AG (3rd column to 33rd column)
const filterRange = groupSettingsSheet.getRange('C1:AG' + lastRow);
filterRange.createFilter();

}

function getSettingsGroup(email) {
Expand Down
6 changes: 5 additions & 1 deletion getMobileDevices.gs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ function getMobileDevices() {
rules.push(rule);
mobileDeviceSheet.setConditionalFormatRules(rules);

const lastRow = mobileDeviceSheet.getLastRow();
const filterRange = mobileDeviceSheet.getRange('B1:G' + lastRow); // Filter columns B through G (including header)
filterRange.createFilter();

const customerId = "my_customer";

let rows = [];
Expand Down Expand Up @@ -78,4 +82,4 @@ function getMobileDevices() {
if (columnsToDelete > 0) {
mobileDeviceSheet.deleteColumns(8, columnsToDelete);
}
}
}
10 changes: 9 additions & 1 deletion getOAuthTokens.gs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ function getTokens() {

// Hide column F
oAuthTokenSheet.hideColumns(6);

// Add note to cell G1
oAuthTokenSheet.getRange("G1").setNote("A light red highlighted row indicates the app uses a restricted or sensitive scope.");

// Apply conditional formatting
const range = oAuthTokenSheet.getRange('A2:G999');
Expand Down Expand Up @@ -123,6 +126,11 @@ function getTokens() {
console.log("Tokens written to Sheet Users: %s", tokens.length);
const dataRange = oAuthTokenSheet.getRange(2, 1, tokens.length, tokens[0].length);
dataRange.setValues(tokens);

// --- Add Filter View ---
const lastRow = oAuthTokenSheet.getLastRow();
const filterRange = oAuthTokenSheet.getRange('A1:G' + lastRow); // Filter columns A through G, starting from row 1
filterRange.createFilter();

// Auto resize columns A, D, E
oAuthTokenSheet.autoResizeColumns(1, 1);
Expand All @@ -135,4 +143,4 @@ function getTokens() {
// Delete columns H-Z
oAuthTokenSheet.deleteColumns(8, 18);
oAuthTokenSheet.deleteColumns(8);
}
}
45 changes: 27 additions & 18 deletions getOrgUnits.gs
Original file line number Diff line number Diff line change
Expand Up @@ -29,39 +29,43 @@ function getOrgUnits(){
headerRange.setFontWeight("bold").setFontColor("#ffffff").setFontFamily("Montserrat");
headerRange.setBackground("#fc3165");

// This code will inventory all OUs in Google Workspace. The org unit IDs are used in other sections of the workbook.
const fileArray = [
[
"Org Name ID",
"Org Unit Name",
"OrgUnit Path",
"Description",
"Parent Org Unit ID",
"Parent Org Unit Path",
],
];

// Fetch and sort org units
const orgUnits = AdminDirectory.Orgunits.list("my_customer", {
type: "ALL",
}).organizationUnits;

// Sort the orgUnits array based on the orgUnitPath
orgUnits.sort((a, b) => {
// Split the paths into components
const pathA = a.orgUnitPath.split("/");
const pathB = b.orgUnitPath.split("/");

// Compare paths component by component
for (let i = 0; i < Math.min(pathA.length, pathB.length); i++) {
if (pathA[i] < pathB[i]) return -1; // a comes before b
if (pathA[i] > pathB[i]) return 1; // a comes after b
}

// If all components match, shorter path comes first
return pathA.length - pathB.length;
});

// Prepare data for the sheet (including headers)
const fileArray = [headers];
orgUnits.forEach((orgUnit) => {
fileArray.push([
orgUnit.orgUnitId.slice(3),
orgUnit.name,
orgUnit.orgUnitPath,
orgUnit.description,
orgUnit.parentOrgUnitId
? orgUnit.parentOrgUnitId.replace(/^id:/, "")
: "",
orgUnit.parentOrgUnitId ? orgUnit.parentOrgUnitId.replace(/^id:/, "") : "",
orgUnit.parentOrgUnitPath,
]);
});

// Write data back to our sheets
orgUnitsSheet
.getRange(1, 1, fileArray.length, fileArray[0].length)
.setValues(fileArray);
// Write data back to the sheet
orgUnitsSheet.getRange(1, 1, fileArray.length, fileArray[0].length).setValues(fileArray);

// Delete columns G-Z
orgUnitsSheet.deleteColumns(7, 20);
Expand All @@ -73,4 +77,9 @@ function getOrgUnits(){
// Define ranges
spreadsheet.setNamedRange('Org2ParentPath', orgUnitsSheet.getRange('E:F'));
spreadsheet.setNamedRange('OrgID2Path', orgUnitsSheet.getRange('A:C'));

// --- Add Filter View ---
const lastRow = orgUnitsSheet.getLastRow();
const filterRange = orgUnitsSheet.getRange('A1:F' + lastRow); // Filter columns A through F (including header)
filterRange.createFilter();
}
7 changes: 6 additions & 1 deletion getSharedDrives.gs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,12 @@ function getSharedDrives() {
rules.push(rule2);
sharedDrivesSheet.setConditionalFormatRules(rules);

// --- Add Filter View ---
const lastRow = sharedDrivesSheet.getLastRow();
const filterRange = sharedDrivesSheet.getRange('D1:J' + lastRow); // Filter columns D through H
filterRange.createFilter();

const endTime = new Date().getTime();
const elapsed = (endTime - startTime) / 1000;
Logger.log("Elapsed Seconds: " + elapsed);
}
}
14 changes: 10 additions & 4 deletions getUsersList.gs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,6 @@ function getUsersList() {
usersSheet.setFrozenRows(1); // Sets headers in sheet and freezes row
usersSheet.getRange(2, 1, users.length, users[0].length).setValues(users); // Adds in user info starting from row 1

// Auto resize all columns
usersSheet.autoResizeColumns(1, usersSheet.getLastColumn());

// Apply conditional formatting
var rangeC = usersSheet.getRange("C2:C1000");
var ruleC = SpreadsheetApp.newConditionalFormatRule()
Expand All @@ -88,6 +85,7 @@ function getUsersList() {
.setBackground("#ffb6c1")
.setRanges([rangeH])
.build();

var ruleHFalse = SpreadsheetApp.newConditionalFormatRule()
.whenTextContains("TRUE")
.setBackground("#b7e1cd")
Expand Down Expand Up @@ -121,6 +119,14 @@ function getUsersList() {
var rules = [ruleC, ruleCFalse, ruleH, ruleHFalse, ruleI, ruleIFalse, ruleD, ruleDFalse];
usersSheet.setConditionalFormatRules(rules);

// --- Add Filter View ---
const lastRow = usersSheet.getLastRow();
const filterRange = usersSheet.getRange('C1:J' + lastRow); // Filter columns C through J
filterRange.createFilter();

// Create named range for columns B, C, D, and E
var namedRange = spreadsheet.setNamedRange('UserStatus', usersSheet.getRange('B2:E1000'));
const namedRange = spreadsheet.setNamedRange('UserStatus', usersSheet.getRange('B2:E' + lastRow));

// Auto resize all columns
usersSheet.autoResizeColumns(1, usersSheet.getLastColumn());
}

0 comments on commit e1182b3

Please sign in to comment.