ソースを参照

Handle verified account restrictions in mini program sign-in

彭峰 4 日 前
親
コミット
8a26336889
3 ファイル変更、111 行追加、18 行削除
  1. 51 18
      index.js
  2. 44 0
      test/login-restrictions.test.cjs
  3. 16 0
      utils/login-restrictions.js

+ 51 - 18
index.js

@@ -9,6 +9,7 @@ let config = {
 }
 const plugin = requirePlugin('fm-plugin')
 const { Parse, checkAuth } = plugin
+const { restrictionMessage, restrictionMessageForUser } = require('./utils/login-restrictions');
 
 // enabledOptions 可能由插件初始化写入;未授权/首登异常时可能为 undefined
 // 避免 data 初始化阶段直接读取 [0] 导致页面直接崩溃。
@@ -69,7 +70,6 @@ Page({
     wx.login({
       success: function (res) {
         if (res.code) {
-          console.log(res);
           // wx.request({
           //   url: "https://server.fmode.cn/api/wxapp/auth_wxapp",
           //   data: {
@@ -211,6 +211,15 @@ Page({
   },
 
   async review(force){
+    const showRestriction = (message) => {
+      this.setData({loading:false});
+      wx.showModal({title:'无法登录',content:message,showCancel:false});
+    };
+    const clearLogin = async () => {
+      try { await Parse.User.logOut(); } catch {}
+      wx.removeStorageSync('sessionToken');
+      wx.removeStorageSync('userLogin');
+    };
     try {
       let options = this.data.options
       let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath
@@ -230,15 +239,29 @@ Page({
       }
 
       let currentUser = Parse.User.current()
-      console.log('===========================================');
-      console.log('======= index.js review 方法 =======');
-      console.log('当前用户:', currentUser ? currentUser.id : '无');
-      console.log('用户手机号:', currentUser?.get('mobile') || '无');
-      console.log('用户名:', currentUser?.get('username') || '无');
-      console.log('Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
-      console.log('userLogin 存储:', wx.getStorageSync('userLogin') || '无');
-      console.log('force 参数:', force);
-      console.log('===========================================');
+      if (currentUser) {
+        const token = currentUser.getSessionToken?.();
+        try {
+          if (!token) throw {code:209};
+          const verified = await Parse.User.become(token);
+          if (!verified?.id || verified.id !== currentUser.id) throw {code:209};
+          currentUser=verified;
+        } catch (err) {
+          if (Number(err?.code)!==209) {
+            this.setData({loading:false});
+            wx.showModal({title:'登录状态待核验',content:'暂时无法连接登录服务,请稍后重试。',showCancel:false});
+            return;
+          }
+          await clearLogin();
+          currentUser=null;
+        }
+        const restriction=restrictionMessageForUser(currentUser);
+        if (restriction) {
+          await clearLogin();
+          showRestriction(restriction);
+          return;
+        }
+      }
       
       // 查询 Company 的 isPublishing 字段
       let isPublishing = false;
@@ -290,16 +313,23 @@ Page({
         console.log('🔐 是否强制登录:', forceAuth);
         
         let r = await checkAuth(forceAuth);
+        const restriction = restrictionMessage(r);
+        if (restriction) {
+          showRestriction(restriction);
+          return;
+        }
         
         console.log('===========================================');
         console.log('======= checkAuth 返回结果 =======');
-        console.log('返回值:', r);
         
         // 重新获取用户信息
         currentUser = Parse.User.current();
-        console.log('checkAuth 后的用户:', currentUser ? currentUser.id : '无');
-        console.log('checkAuth 后的手机号:', currentUser?.get('mobile') || '无');
-        console.log('checkAuth 后的 Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
+        const activeRestriction = restrictionMessageForUser(currentUser);
+        if (activeRestriction) {
+          await clearLogin();
+          showRestriction(activeRestriction);
+          return;
+        }
         console.log('===========================================');
         
         // 如果强制登录但用户未登录,不允许继续访问
@@ -317,10 +347,8 @@ Page({
           if (currentUser && currentUser.get('mobile')) {
             wx.setStorageSync("userLogin", currentUser.id);
             console.log('✅ 授权登录成功,已设置 userLogin:', currentUser.id);
-            console.log('✅ 用户手机号:', currentUser.get('mobile'));
           } else {
             console.warn('⚠️ checkAuth 返回成功,但用户没有手机号!');
-            console.warn('   用户对象:', currentUser);
           }
           
           // 禁用扫码相关统计/来源记录
@@ -404,10 +432,15 @@ Page({
       });
     }
     catch (err) {
-      console.log('❌ review 方法出错:', err);
+      const restriction = restrictionMessage(err);
+      if (restriction) {
+        showRestriction(restriction);
+        return;
+      }
+      console.log('登录未完成');
       
       /* 登录身份信息到期,重新登陆 */
-      if((err?.message?.indexOf('Session token is expired') != -1 || err?.message?.indexOf('Invalid session token') != -1) && !force){
+      if((Number(err?.code)===209 || /Session token is expired|Invalid session token/.test(err?.message || '')) && !force){
         console.log('⚠️ Session Token 过期,准备重新登录');
         
         // 保存需要保留的数据

+ 44 - 0
test/login-restrictions.test.cjs

@@ -0,0 +1,44 @@
+const assert=require('node:assert/strict');
+const test=require('node:test');
+const vm=require('node:vm');
+const fs=require('node:fs');
+
+function review({cached=false,result,throwReply=false}) {
+  const state={revoked:0,prompts:[],routes:[]};
+  let current=cached?{id:'expired-fixture',getSessionToken:()=> 'test-only'}:null;
+  const Parse={User:{current:()=>current,become:async()=>{throw {code:209};},
+    logOut:async()=>{state.revoked++;current=null;}},
+    Query:class{equalTo(){} select(){} async first(){return {get:()=>false};}}};
+  const plugin={Parse,checkAuth:async()=>{
+    if(throwReply)throw result;
+    if(result===true)current={id:'restored-fixture',get:key=>key==='mobile'?'synthetic':false};
+    return result;
+  }};
+  let page;
+  const requireInPage=name=>name==='config.js'?{default:{}}:require('../'+name.replace(/^\.\//,''));
+  const context={require:requireInPage,requirePlugin:()=>plugin,console:{log(){},warn(){},error(){}},
+    wx:{getStorageSync:()=>undefined,removeStorageSync(){},setStorageSync(){},
+      redirectTo:args=>state.routes.push(args.url),showModal:args=>state.prompts.push(args.content)},
+    getApp:()=>({globalData:{rootPage:'/fixture',company:'tenant-test'}}),
+    Page:value=>{page=value;}};
+  vm.runInNewContext(fs.readFileSync(new URL('../index.js','file://'+__filename),'utf8'),context);
+  page.setData=()=>{}; page.getCompanyServerExpire=async()=>true;
+  return {state,run:()=>page.review()};
+}
+test('an expired session is dropped and the verified freeze stops routing',async()=>{
+  const check=review({cached:true,result:{code:119,error:'ACCOUNT_FROZEN'}});
+  await check.run();
+  assert.equal(check.state.revoked,1);
+  assert.equal(check.state.routes.length,0);
+  assert.match(check.state.prompts[0],/保护性冻结/);
+});
+test('shows provider ban rejection and allows a later successful verified login',async()=>{
+  const denied=review({result:{error:{error:'ACCOUNT_BANNED'}},throwReply:true});
+  await denied.run();
+  assert.equal(denied.state.routes.length,0);
+  assert.match(denied.state.prompts[0],/封禁/);
+  const restored=review({result:true});
+  await restored.run();
+  assert.deepEqual(restored.state.routes,['/fixture']);
+});
+

+ 16 - 0
utils/login-restrictions.js

@@ -0,0 +1,16 @@
+function restrictionMessage(reply) {
+  for (const body of [reply, reply?.error, reply?.data]) {
+    const markers = [body?.code, body?.message, body?.mess, body?.error];
+    if (markers.includes('ACCOUNT_BANNED')) return '此账号已被封禁,无法登录。请联系客服。';
+    if (markers.includes('ACCOUNT_FROZEN')) return '此账号已被保护性冻结,暂时无法登录。请联系客服核验。';
+  }
+  return undefined;
+}
+
+function restrictionMessageForUser(user) {
+  if (user?.get('isBanned') === true) return restrictionMessage({code:'ACCOUNT_BANNED'});
+  if (user?.get('isDisabled') === true) return restrictionMessage({code:'ACCOUNT_FROZEN'});
+  return undefined;
+}
+
+module.exports = {restrictionMessage,restrictionMessageForUser};