星期六, 5月 16, 2026

[GAS] OTP 登錄

在了解 [GAS] CacheService 如何使用後,該筆記範例是 OTP 登錄範例,OTP (One Time Password) 相關操作都會在 CacheService 上進行
gs Code
/**
 * 處理 Web App 的 HTTP GET 請求,回傳使用者介面。
 * @param {Object} e - 事件物件 (GET 參數)。
 * @return {HtmlOutput} 渲染後的 HTML 畫面。
 */
function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('Index')
      .setTitle('OTP 登入')
      .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

/**
 * 產生並發送 OTP 至指定 Email,同時將 OTP 寫入 CacheService。
 * @param {string} email - 使用者的電子郵件地址。
 * @return {Object} 包含執行結果的狀態物件 {success: boolean, message: string}。
 */
function generateAndSendOTP(email) {
  try {
    if (!email || !email.includes('@')) {
      return { success: false, message: '請提供有效的 Email 地址格式' };
    }

    // 產生 6 位數隨機 OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    // 取得 Script 層級的 Cache,將 email 當作 Key,OTP 當作 Value
    const cache = CacheService.getScriptCache();
    // 設定快取保留時間為 300 秒 (5 分鐘)
    cache.put(email, otp, 300);

    // 寄送包含 OTP 的電子郵件
    const subject = '您的系統登入一次性密碼 (OTP)';
    const body = '您好,\n\n您的登入驗證碼為:' + otp + '\n此驗證碼將於 5 分鐘後失效。\n\n若非本人操作請忽略此信件。';
    GmailApp.sendEmail(email, subject, body);

    return { success: true, message: 'OTP 已發送至您的信箱,請於 5 分鐘內輸入。' };
  } catch (error) {
    return { success: false, message: '系統錯誤:' + error.message };
  }
}

/**
 * 驗證使用者輸入的 OTP 是否與 CacheService 中的記錄相符。
 * @param {string} email - 使用者的電子郵件地址。
 * @param {string} otp - 使用者輸入的 OTP。
 * @return {Object} 包含驗證結果的狀態物件 {success: boolean, message: string}。
 */
function verifyOTP(email, otp) {
  try {
    const cache = CacheService.getScriptCache();
    const cachedOtp = cache.get(email);

    if (!cachedOtp) {
      return { success: false, message: 'OTP 已過期或不存在,請重新獲取。' };
    }

    if (cachedOtp === otp) {
      // 驗證成功後,基於安全性應立即移除 Cache 中的 OTP
      cache.remove(email);
      return { success: true, message: '驗證成功!歡迎登入系統。' };
    } else {
      return { success: false, message: 'OTP 錯誤,請重新輸入。' };
    }
  } catch (error) {
    return { success: false, message: '驗證時發生系統錯誤:' + error.message };
  }
}
執行結果

收到 OTP email

使用 OTP 密碼登錄

Index.html 不是該筆記重點,就不放在文章上囉

沒有留言:

張貼留言