ソースを参照

fix(miniprogram): restore authorized web-view destination after login

彭峰 6 日 前
親
コミット
a3530e6fdf

+ 2 - 1
app.json

@@ -1,6 +1,7 @@
 {
   "pages": [
-    "index"
+    "index",
+    "components/app-auth/index"
   ],
   "subpackages": [
     {

+ 24 - 151
common-page/pages/web-view/index.js

@@ -1,4 +1,5 @@
 // common-page/pages/web-view/index.js
+const { requestedTarget, withQuery } = require('../../../utils/web-view-target');
 const Parse = getApp().Parse;
 const company = getApp().globalData.company;
 const DEBUG_WEBVIEW = false;
@@ -36,91 +37,36 @@ Page({
     onLoad: async function (options) {
         debugLog('======= web-view 页面加载 =======');
         
-        // 1. 先检查用户登录状态
-        const loginCheck = await this.checkUserLogin(options);
-        if (!loginCheck) {
-            debugLog('⚠️ 用户未登录或没有手机号,已跳转到授权页面');
-            return; // 停止后续加载
-        }
-        debugLog('✅ 用户已登录且有手机号,继续加载 web-view');
-        
-        // 2. 解码 URL
-        let path = decodeURIComponent(options.path || '');
-        const isSkipAuth = options.skipAuth === 'true';
-        const isHomePath = /^https?:\/\/www\.yuban\.co\/home([/?#]|$)/.test(path);
-
-        // 引导页直达 H5 首页时走快速路径:
-        // 仅补齐缺失的登录/欢迎参数,避免额外 Parse 查询造成首开延迟。
-        if (isSkipAuth && isHomePath) {
-            path = this.ensureHomeAuthQuery(path);
-            this.setData({ path });
+        const destination = requestedTarget(options);
+        if (!destination) {
+            wx.showToast({title:'链接不可用',icon:'none'});
             return;
         }
-
-        debugLog('原始 options.path:', options.path);
-        debugLog('解码后的 path:', path);
-
-        // 拼接额外参数(避免重复添加已存在的参数)
-        let hasQuery = path.indexOf('?') !== -1;
-        let parsm = hasQuery ? '&' : '?';
-        let params = [];
-        
-        // 提取 path 中已有的参数
-        let existingParams = new Set();
-        if (hasQuery) {
-            const queryString = path.split('?')[1];
-            if (queryString) {
-                queryString.split('&').forEach(param => {
-                    const key = param.split('=')[0];
-                    existingParams.add(key);
-                });
-            }
-        }
-
-        // 只添加 path 中不存在的参数
-        for (const key in options) {
-            if(key != 'path' && key != 'url' && !existingParams.has(key)){
-                params.push(key + '=' + options[key]);
-            }
-        }
-
-        // 添加用户信息,确保 H5 能获取到当前用户身份(用于扣减流量等操作)
-        const currentUser = Parse.User.current();
-        if (currentUser) {
-            // 添加 userId
-            if (!existingParams.has('userId')) {
-                params.push('userId=' + currentUser.id);
-            }
-            // 添加 token (sessionToken)
-            const sessionToken = currentUser.getSessionToken();
-            if (sessionToken && !existingParams.has('token')) {
-                params.push('token=' + sessionToken);
-            }
-            // 添加 mobile
-            const mobile = currentUser.get('mobile');
-            if (mobile && !existingParams.has('mobile')) {
-                params.push('mobile=' + mobile);
+        const isHome = /^https:\/\/www\.yuban\.co\/home(?:[/?#]|$)/.test(destination);
+        const homeStartup = isHome && options.skipAuth === 'true';
+        if (!homeStartup && !await this.checkUserLogin(options)) return;
+
+        let user = Parse.User.current();
+        if (homeStartup && !user) {
+            const saved = wx.getStorageSync('sessionToken');
+            if (saved) {
+                try { user = await Parse.User.become(saved); }
+                catch (_) { wx.removeStorageSync('sessionToken'); wx.removeStorageSync('userLogin'); }
             }
         }
-
-        if(params.length > 0) {
-            parsm = parsm + params.join('&');
-            path = path + parsm;
+        const params = homeStartup ? {fromStartup:'1',source:'wechat-miniprogram'} : {};
+        if (user) {
+            params.token = user.getSessionToken();
+            params.userId = user.id;
+            params.mobile = user.get('mobile');
         }
+        this.setData({ path: withQuery(destination, params) });
+        if (homeStartup) return;
 
-        debugLog('最终 web-view URL:', path);
-        debugLog('URL 长度:', path.length);
-
-        this.setData({
-            path: path
-        })
-
-        // 立即设置标题
         const passedStoreName = options.storeName ? decodeURIComponent(options.storeName) : '';
         const passedStoreId = options.storeId || '';
         // /home 场景下默认不需要门店标题:跳过 ShopStore 的 Parse 查询以提速。
         // 这里根据 H5 path 判断:例如 https://www.yuban.co/home?token=...&skipAuth=true...
-        const isHome = isHomePath;
 
         if (passedStoreName) {
             this.setNavigationTitle(passedStoreName);
@@ -144,12 +90,6 @@ Page({
         try {
             debugLog('🔍 开始检查用户登录状态...');
             
-            // 检查是否有 skipAuth 参数(用于跳过登录检查)
-            if (options.skipAuth === 'true') {
-                debugLog('ℹ️ 检测到 skipAuth 参数,跳过登录检查');
-                return true;
-            }
-
             // 检查是否是扫码进入
             const isScanEntry = options && (options.storeId && (options.scanCount || options.partnerId || options.userId || options.employeeId));
             if (isScanEntry) {
@@ -189,11 +129,8 @@ Page({
             debugLog('⚠️ 用户未完整登录,准备跳转到授权页面');
             
             // 构建返回 URL(登录成功后返回当前页面)
-            const currentPath = options.path || '';
-            const returnUrl = encodeURIComponent(currentPath);
-            
-            debugLog('🔗 returnUrl:', returnUrl);
-            
+            const returnUrl = encodeURIComponent(requestedTarget(options));
+
             // 跳转到授权页面,并传递 returnUrl
             wx.redirectTo({
                 url: `/components/app-auth/index?returnUrl=${returnUrl}`,
@@ -234,7 +171,7 @@ Page({
             debugLog('checkUserLogin error');
             
             // 出错时也跳转到授权页面
-            const returnUrl = options.path ? encodeURIComponent(options.path) : '';
+            const returnUrl = encodeURIComponent(requestedTarget(options));
             wx.redirectTo({
                 url: `/components/app-auth/index?returnUrl=${returnUrl}`,
                 fail: () => {
@@ -284,70 +221,6 @@ Page({
 
     },
 
-    /**
-     * 直达 /home 时补齐 token/userId/mobile/fromStartup,不覆盖 URL 已有值。
-     */
-    ensureHomeAuthQuery: function (path) {
-        try {
-            const hasQuery = path.indexOf('?') !== -1;
-            const existingParams = new Set();
-            if (hasQuery) {
-                const queryString = path.split('?')[1] || '';
-                queryString.split('&').forEach((param) => {
-                    const key = param.split('=')[0];
-                    if (key) existingParams.add(key);
-                });
-            }
-
-            const append = [];
-            if (!existingParams.has('fromStartup')) {
-                append.push('fromStartup=1');
-            }
-            if (!existingParams.has('source')) {
-                append.push('source=wechat-miniprogram');
-            }
-
-            let token = null;
-            let userId = null;
-            let mobile = null;
-            try {
-                const currentUser = Parse && Parse.User ? Parse.User.current() : null;
-                if (currentUser) {
-                    token = currentUser.getSessionToken() || null;
-                    userId = currentUser.id || null;
-                    mobile = currentUser.get('mobile') || null;
-                }
-            } catch (e) {
-                // ignore
-            }
-            try {
-                if (!token) token = wx.getStorageSync('sessionToken') || null;
-                if (!userId) userId = wx.getStorageSync('userLogin') || null;
-                if (!mobile) {
-                    const userInfo = wx.getStorageSync('userInfo') || {};
-                    mobile = userInfo.mobile || null;
-                }
-            } catch (e) {
-                // ignore
-            }
-
-            if (token && !existingParams.has('token')) {
-                append.push('token=' + encodeURIComponent(token));
-            }
-            if (userId && !existingParams.has('userId')) {
-                append.push('userId=' + encodeURIComponent(userId));
-            }
-            if (mobile && !existingParams.has('mobile')) {
-                append.push('mobile=' + encodeURIComponent(mobile));
-            }
-
-            if (append.length === 0) return path;
-            return path + (hasQuery ? '&' : '?') + append.join('&');
-        } catch (e) {
-            return path;
-        }
-    },
-
     /**
      * 处理来自 H5 页面的消息
      */

+ 7 - 21
components/app-auth/index.js

@@ -1,3 +1,4 @@
+const { readTarget } = require('../../utils/web-view-target');
 let Parse = getApp().Parse;
 let company = getApp().globalData.company
 const request = require("../../utils/request");
@@ -504,30 +505,15 @@ Page({
     
     // 检查是否有 returnUrl 参数(从 H5 页面传递过来)
     const currentPage = pages[pages.length - 1];
-    const returnUrl = currentPage?.options?.returnUrl;
-    
-    if (returnUrl) {
-      console.log('📍 检测到 returnUrl 参数:', returnUrl);
-      
-      // 如果是 web-view 页面,跳转回去
-      const decodedUrl = decodeURIComponent(returnUrl);
-      console.log('🔙 准备跳转回 H5 页面:', decodedUrl);
-      
-      wx.navigateTo({
-        url: `/common-page/pages/web-view/index?path=${encodeURIComponent(decodedUrl)}`,
-        success: () => {
-          console.log('✅ 跳转回 H5 页面成功');
-          console.log('===========================================');
-        },
-        fail: (err) => {
-          console.error('❌ 跳转回 H5 页面失败:', err);
-          // 降级:正常返回上一页
-          this.normalBackLoad();
-        }
+    const target = readTarget(currentPage?.options?.returnUrl);
+    if (target) {
+      wx.redirectTo({
+        url: '/common-page/pages/web-view/index?path=' + encodeURIComponent(target),
+        fail: () => this.normalBackLoad(),
       });
       return;
     }
-    
+
     // 没有 returnUrl,执行正常的返回逻辑
     this.normalBackLoad();
   },

+ 56 - 0
test/governance-smoke.test.cjs

@@ -32,3 +32,59 @@ test('页面入口和分享可解析,移除的传输函数不再导出', t =>
   assert.ok(pages.includes(page.onShareAppMessage().path));
   assert.equal(Object.hasOwn(util, 'sentRes'), false);
 });
+
+test('通用业务页经已登记登录页恢复原目标,保留查询与片段', async () => {
+  const vm = require('node:vm');
+  const target = require('../utils/web-view-target');
+  const manifest = require('../app.json');
+  const routes = new Set([...manifest.pages,...manifest.subpackages.flatMap(pkg=>pkg.pages.map(page=>pkg.root+'/'+page))]);
+  const history = [];
+  const storage = new Map();
+  let user, currentPage;
+  const app = {Parse:{User:{current:()=>user}},globalData:{company:'synthetic'},checkAuth:async()=>Boolean(user)};
+  const wx = {
+    getStorageSync:key=>storage.get(key),setStorageSync:(key,value)=>storage.set(key,value),
+    redirectTo:({url})=>{const address=new URL(url,'https://local.invalid');assert.ok(routes.has(address.pathname.slice(1)));history.push(address);},
+    showToast(){},
+  };
+  const load = file => {
+    vm.runInNewContext(fs.readFileSync(path.join(root,file),'utf8'), {
+      wx,getApp:()=>app,getCurrentPages:()=>[currentPage],console:{log(){},debug(){},error(){},warn(){}},
+      require:name=>name.endsWith('web-view-target')?target:{},
+      Page:def=>{currentPage={...def,data:{...def.data},setData(value){Object.assign(this.data,value);}};},
+    });
+    return currentPage;
+  };
+  const original='https://www.yuban.co/user-profile/memory-cleanup?tab=people&label=a%26b#family';
+  const web=load('common-page/pages/web-view/index.js');
+  const opts={path:encodeURIComponent(original),source:'mini'};
+  await web.onLoad(opts);
+  const authRoute=history.pop();
+  assert.equal(authRoute.pathname,'/components/app-auth/index');
+  assert.equal(web.data.path,'');
+  const expected=original.replace('#family','&source=mini#family');
+  assert.equal(authRoute.searchParams.get('returnUrl'),expected);
+  const auth=load('components/app-auth/index.js');auth.options=Object.fromEntries(authRoute.searchParams);
+  user={id:'fixture-member',get:key=>({mobile:'fixture-mobile',nickname:'测试会员'})[key],getSessionToken:()=>'fixture-session'};
+  await auth.getUserProfile();
+  const returned=history.pop();assert.equal(returned.pathname,'/common-page/pages/web-view/index');
+  assert.equal(returned.searchParams.get('path'),expected);
+  const resumed=load('common-page/pages/web-view/index.js');
+  await resumed.onLoad(Object.fromEntries(returned.searchParams));
+  const final=new URL(resumed.data.path);
+  assert.equal(final.pathname,'/user-profile/memory-cleanup');assert.equal(final.hash,'#family');
+  assert.equal(final.searchParams.get('label'),'a&b');assert.equal(final.searchParams.get('source'),'mini');
+  assert.equal(final.searchParams.get('token'),'fixture-session');assert.deepEqual(final.searchParams.getAll('userId'),['fixture-member']);
+});
+
+test('引导页会话信息与已有受控业务路径兼容', () => {
+  const {readTarget,requestedTarget,withQuery}=require('../utils/web-view-target');
+  const path='https://www.yuban.co/home?fromStartup=1&source=wechat-miniprogram#start';
+  const url=new URL(withQuery(requestedTarget({path:encodeURIComponent(path),skipAuth:'true'}),{token:'fixture-current'}));
+  assert.equal(url.hash,'#start');assert.equal(url.searchParams.getAll('source').length,1);assert.equal(url.searchParams.has('skipAuth'),false);
+  assert.equal(readTarget('%broken'),'');
+  for(const name of ['products','cases','home']) {
+    const legacy='https://app.fmode.cn/dev/pobingfeng/owner/nav/'+name+'?storeId=sample';
+    assert.equal(readTarget(encodeURIComponent(legacy)),legacy);
+  }
+});

+ 46 - 0
utils/web-view-target.js

@@ -0,0 +1,46 @@
+// Keep query strings intact on both raw and WeChat-encoded page options.
+function readTarget(value) {
+  if (typeof value !== 'string' || !value || value.length > 8192) return '';
+  let target = value;
+  if (!target.startsWith('https://')) {
+    try { target = decodeURIComponent(value); } catch (_) { return ''; }
+  }
+  if (/[\\\s\u0000-\u001f]/.test(target)) return '';
+  const matched = /^https:\/\/([^/?#]+)([^?#]*)(?:[?#]|$)/.exec(target);
+  if (!matched) return '';
+  if (matched[1] === 'www.yuban.co') return target;
+  if (matched[1] === 'app.fmode.cn' && /^\/dev\/pobingfeng\/owner\/nav\/(?:products|cases|home)\/?$/.test(matched[2])) return target;
+  return '';
+}
+
+function queryKey(part) {
+  try { return decodeURIComponent(part.split('=')[0]); } catch (_) { return ''; }
+}
+
+function withQuery(target, values = {}, removeIdentity = false) {
+  const hashAt = target.indexOf('#');
+  const url = hashAt < 0 ? target : target.slice(0, hashAt);
+  const hash = hashAt < 0 ? '' : target.slice(hashAt);
+  const index = url.indexOf('?');
+  const base = index < 0 ? url : url.slice(0, index);
+  let parts = index < 0 ? [] : url.slice(index + 1).split('&').filter(Boolean);
+  if (removeIdentity) parts = parts.filter(part => !['token','userId','mobile'].includes(queryKey(part)));
+  const keys = new Set(parts.map(queryKey));
+  for (const [key,value] of Object.entries(values)) {
+    if (keys.has(key) || value === '' || value == null) continue;
+    parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)));
+  }
+  return base + (parts.length ? '?' + parts.join('&') : '') + hash;
+}
+
+function requestedTarget(options = {}) {
+  const target = readTarget(options.path);
+  if (!target) return '';
+  const values = {};
+  for (const [key,value] of Object.entries(options)) {
+    if (!['path','url','skipAuth','token','userId','mobile','__proto__','constructor','prototype'].includes(key) && typeof value === 'string') values[key] = value;
+  }
+  return withQuery(target, values, true);
+}
+
+module.exports = { readTarget, requestedTarget, withQuery };