- 執行身份:我 (gmail 信箱)
- 誰可以存取:所有人
- 執行身份:存取網頁應用程式的使用者
- 誰可以存取:所有已登入 Google 帳戶的使用者
使用者 Email
透過 getActiveUser() 來存取 Google 帳號 Email
Gets information about the current user. If security policies do not allow access to the user's identity, User.getEmail() returns a blank string. The circumstances in which the email address is available vary: for example, the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user). However, these restrictions generally do not apply if the developer runs the script themselves or belongs to the same Google Workspace domain as the user.
網頁存取名單
在 GAS PropertyService 內設定存取存取名單,存取名單已逗號 (,) 分隔,例如:123@gmail.com,456@gmail.com,當然也可以放在 Google Sheet 或第三方資料庫來管理存取名單
gs Code
/**
* 系統配置參數
* @constant {Object}
*/
const CONFIG = {
PROPERTY_KEY: 'WHITELIST' // 儲存在指令碼屬性中的鍵名
};
/**
* 從指令碼屬性 (PropertiesService) 中獲取白名單。
* @returns {string[]} 允許存取的 Google 帳號信箱陣列。
*/
const getAllowedEmails = () => {
const whitelistStr = PropertiesService.getScriptProperties().getProperty(CONFIG.PROPERTY_KEY);
if (!whitelistStr) {
console.warn('目前沒有設定任何白名單。');
return [];
}
// 將字串轉為陣列,過濾空白並轉為小寫
return whitelistStr.split(',')
.map(email => email.trim().toLowerCase())
.filter(email => email !== '');
};
/**
* 處理 Web App 的 HTTP GET 請求。
* @param {Object} e - 事件物件。
* @returns {GoogleAppsScript.HTML.HtmlOutput} 根據使用者權限回傳對應的 HTML 頁面。
*/
const doGet = (e) => {
const currentUserEmail = Session.getActiveUser().getEmail().toLowerCase();
const allowedEmails = getAllowedEmails();
if (allowedEmails.includes(currentUserEmail)) {
// 驗證通過
const template = HtmlService.createTemplateFromFile('Index');
template.userEmail = currentUserEmail;
return template.evaluate().setTitle('系統主控台');
} else {
// 驗證失敗
const template = HtmlService.createTemplateFromFile('Error');
template.userEmail = currentUserEmail;
return template.evaluate().setTitle('存取被拒絕');
}
};
Index.html 和 Error.html 就不特別列出來囉
實際執行
進入網頁時假如沒有登錄 Google 帳號,會出現 Google 登錄畫面
登錄 Google 帳號後則是檢查該帳號是否在存取白名單內
限制
實作發現,原來 getActiveUser() 在 [執行身份:我 (gmail 信箱)] 時,使用者執行網頁時會回傳空值,該情況只有執行身份信箱使用者可以透過 getActiveUser() 取得 gmail 資訊
[執行身份:存取網頁應用程式的使用者] 時,使用者執行網頁時雖然 getActiveUser() 可以取得 gmail 資訊進一步根據存取名單判斷是否有權限,但該身分初次存取網頁需授予權限,授予權限範圍則是依網頁使用相關服務不一,至少會要求存取使用者帳戶資訊,其實部屬畫面上就有簡易文字說明
原以為 [執行身份:我 (gmail 信箱)] 會類似一個服務帳號,該帳號擁有權限存取 Google 相關服務,而 getActiveUser() 則是可以抓到使用者 gmail 資訊,兩者搭配來實作存取名單功能,但在 GAS 內部架構下看起來沒有這麼理想






沒有留言:
張貼留言