Skip to content

Instantly share code, notes, and snippets.

@namnv609
Created August 3, 2020 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namnv609/e9df6a33ac066570745db29bf753265c to your computer and use it in GitHub Desktop.
Save namnv609/e9df6a33ac066570745db29bf753265c to your computer and use it in GitHub Desktop.
Write Content-Security-Policy header log to Google Spreadsheet
/**
* Name: CSP Report Log
* Description: Write Content-Security-Policy header log to Google Spreadsheet
* Author: NamNV609 <namnv609@gmail.com>
* Homepage: https://github.com/namnv609
* License: MIT
*/
const SHEET_NAME = "<Sheet Name>";
const SCRIPT_PROP = PropertiesService.getScriptProperties();
const MILISEC_PER_SECOND = 1000;
const DOCUMENT_LOCK_TIMEOUT = 30 * MILISEC_PER_SECOND;
const HEADER_ROW_IDX = 1;
function setup() {
const doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("docId", doc.getId());
}
function doPost(evt) {
const responseContent = {status: true};
const docLockService = LockService.getDocumentLock();
docLockService.waitLock(DOCUMENT_LOCK_TIMEOUT);
try {
const doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("docId"));
const sheet = doc.getSheetByName(SHEET_NAME);
const sheetHeaders = sheet.getRange(HEADER_ROW_IDX, 1, 1, sheet.getLastColumn()).getValues()[0];
const nextRowIdx = sheet.getLastRow() + 1;
const cspReportContent = JSON.parse(evt.postData.contents)["csp-report"];
const rowContent = [];
for (let colIdx in sheetHeaders) {
let headerName = sheetHeaders[colIdx];
if (headerName == "created-at") {
rowContent.push(new Date());
} else {
rowContent.push(cspReportContent[headerName]);
}
}
sheet.getRange(nextRowIdx, 1, 1, rowContent.length).setValues([rowContent]);
} catch (err) {
responseContent = {status: false, message: err.message};
} finally {
docLockService.releaseLock();
}
return ContentService.createTextOutput(JSON.stringify(responseContent)).setMimeType(ContentService.MimeType.JSON);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment