iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
自我挑戰組

從無到有打造驗證碼共享的 Line 機器人系列 第 26

用 Line LIFF APP 實現信箱驗證綁定功能(3) - 修改流程實現認證時效檢驗

因為前幾天我們新增了 verification_code 這張表的欄位,調整了發送認證碼的流程,並且設定該認證碼在發送後只有10分鐘時效,這樣一來在原先處理檢驗認證碼的程式邏輯上也要作出修改。

修改收到認證碼後檢驗的流程

因為我們在發送認證碼時,已經將10分鐘後的 timestamp 寫入了 verification_codeexpire_at,所以我們只要檢視這個欄位就能實現認證碼時效檢驗的功能。

修改 tagVerificationCode

有兩個修改的重點:

  • 在 verification_code 找到認證碼後,檢查:
    1. 該列的 userId 是否符合發送時紀錄的值
    2. bind_at 是否為空
    3. expire_at 是否大於等於現在時間
  • 若檢驗都通過,則在 bind_at 押上現在時間,並且將 users sheet 對應的使用者欄位 is_verifed 設為 true
function tagVerificationCode(target, userId) {
  const sheet = ReadMailAndInsertToGoogleSheet.connectToSheet('verification_code');
  const searchResult = ReadMailAndInsertToGoogleSheet.searchColumnValue(sheet, 'code', target);
  if (searchResult !== -1) {
    const targetRowIndex = searchResult+2;
    const targetRowRange = sheet.getRange(targetRowIndex, 2, 1, 4);
    var targetRowValue = targetRowRange.getValues()[0];
    if ((targetRowValue[0] === userId) && (targetRowValue[1].length === 0) && checkExpireAtWithNow(targetRowValue[3])) {
      // write back bind_at
      targetRowValue[1] = new Date();
      targetRowRange.setValues([targetRowValue]);
      // create or update user
      upsertUserInfo(userId, {'is_verifed': true});
      return true;
    }
  }
  return false;
}

function checkExpireAtWithNow(expireAt) {
    const now = Math.floor(Date.now() / 1000);
    return expireAt >= now;
}

使用 Line Messaging 切換圖文選單

因為使用者已經認證成功了,所以這時可以根據前一天的教學,將身分認證的圖文選單切換為獲取驗證碼的圖文選單

新增 changeRichMenuAfterBindSuccess

新增 changeRichMenuAfterBindSuccess 負責切換 userId 的圖文選單為獲取驗證碼

function changeRichMenuAfterBindSuccess(userId) {
   // RICH_MENU_ID_AFTER_BIND_SUCCESS 是獲取驗證碼圖文選單的 rich menu id
       UrlFetchApp.fetch(`https://api.line.me/v2/bot/user/${userId}/richmenu/${RICH_MENU_ID_AFTER_BIND_SUCCESS}`, {
    'headers': {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN
    },
    'method': 'post'
  });
}

測試是否有正常切換選單

可以新增一個測試函式,並且在 GAS 專案執行此函式,測試是否有正常切換圖文選單
p.s. Line User Id 現在應該可以在 Line Bot - 驗證碼小幫手 按下 執行身份認證 後,從 Google Sheet 的 verification_code 找到

function testChangeRichMenuAfterBindSuccess(){
  changeRichMenuAfterBindSuccess('YOUR_LINE_USER_ID');
}

這幾天實作的功能都是在整個認證流程中不可或缺的功能模組,最後只要組裝起來就可以完成整個身份認證流程囉~明天繼續努力!


上一篇
Line Messaging API 切換圖文選單 Rich Menu
下一篇
用 Line LIFF APP 實現信箱驗證綁定功能(4) - 表單驗證電子郵件地址
系列文
從無到有打造驗證碼共享的 Line 機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言