Created
August 3, 2020 09:20
-
-
Save namnv609/e9df6a33ac066570745db29bf753265c to your computer and use it in GitHub Desktop.
Write Content-Security-Policy header log to Google Spreadsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Name: CSP Report Log | |
* Description: Write Content-Security-Policy header log to Google Spreadsheet | |
* Author: NamNV609 <[email protected]> | |
* 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