hookehuyr

feat(auth): 重构静默授权逻辑并优化Dashboard数据刷新

- 将silentAuth从Promise回调改为async/await实现,提高可读性
- 增加用户家庭状态检查,未加入家庭时跳转欢迎页
- 在Dashboard页面使用useLoad触发静默授权
- 提取数据刷新逻辑到独立函数refreshDashboardData
- 移除app.js中冗余的授权跳转代码
1 /* 1 /*
2 * @Date: 2025-06-28 10:33:00 2 * @Date: 2025-06-28 10:33:00
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2025-09-01 14:32:25 4 + * @LastEditTime: 2025-09-12 12:10:06
5 * @FilePath: /lls_program/src/app.js 5 * @FilePath: /lls_program/src/app.js
6 * @Description: 文件描述 6 * @Description: 文件描述
7 */ 7 */
...@@ -18,11 +18,11 @@ const App = createApp({ ...@@ -18,11 +18,11 @@ const App = createApp({
18 // 缓存没有权限的地址 18 // 缓存没有权限的地址
19 const router = routerStore(); 19 const router = routerStore();
20 router.add(path); 20 router.add(path);
21 - if (!wx.getStorageSync("sessionid")) { 21 + // if (!wx.getStorageSync("sessionid")) {
22 - wx.navigateTo({ 22 + // wx.navigateTo({
23 - url: '/pages/auth/index' 23 + // url: '/pages/auth/index'
24 - }) 24 + // })
25 - } 25 + // }
26 }, 26 },
27 onShow() { 27 onShow() {
28 }, 28 },
......
...@@ -156,7 +156,7 @@ ...@@ -156,7 +156,7 @@
156 <script setup> 156 <script setup>
157 import "./index.less"; 157 import "./index.less";
158 import { ref, computed, onMounted } from 'vue'; 158 import { ref, computed, onMounted } from 'vue';
159 -import Taro, { useDidShow, useReady } from '@tarojs/taro'; 159 +import Taro, { useDidShow, useReady, useLoad } from '@tarojs/taro';
160 import { Setting, Photograph, Category } from '@nutui/icons-vue-taro'; 160 import { Setting, Photograph, Category } from '@nutui/icons-vue-taro';
161 import BottomNav from '../../components/BottomNav.vue'; 161 import BottomNav from '../../components/BottomNav.vue';
162 import TotalPointsDisplay from '@/components/TotalPointsDisplay.vue'; 162 import TotalPointsDisplay from '@/components/TotalPointsDisplay.vue';
...@@ -171,6 +171,7 @@ const defaultFamilyCover = 'https://cdn.ipadbiz.cn/lls_prog/images/default-famil ...@@ -171,6 +171,7 @@ const defaultFamilyCover = 'https://cdn.ipadbiz.cn/lls_prog/images/default-famil
171 const defaultAvatar = 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg' 171 const defaultAvatar = 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'
172 // 接口信息 172 // 接口信息
173 import { getFamilyDashboardAPI } from '@/api/family' 173 import { getFamilyDashboardAPI } from '@/api/family'
174 +import { silentAuth } from '@/utils/authRedirect'
174 175
175 const todaySteps = ref(0); 176 const todaySteps = ref(0);
176 const isWeRunAuthorized = ref(false); 177 const isWeRunAuthorized = ref(false);
...@@ -308,34 +309,77 @@ const handleAdClick = (targetPage) => { ...@@ -308,34 +309,77 @@ const handleAdClick = (targetPage) => {
308 const family_id = ref(''); 309 const family_id = ref('');
309 const totalFamilySteps = ref(0); 310 const totalFamilySteps = ref(0);
310 311
311 -useDidShow(async () => { 312 +/**
312 - // 直接获取家庭首页数据,同时判断是否加入家庭 313 + * 刷新Dashboard页面数据
313 - const { code, data } = await getFamilyDashboardAPI(); 314 + */
314 - if (code) { 315 +const refreshDashboardData = async () => {
315 - // 获取家庭ID 316 + try {
316 - family_id.value = data.family.id; 317 + console.log('开始刷新Dashboard页面数据');
318 + const { code, data } = await getFamilyDashboardAPI();
319 + if (code) {
320 + // 获取家庭ID
321 + family_id.value = data.family.id;
322 +
323 + // 设置页面数据
324 + pendingPoints.value = data.pending_points || [];
325 + familyMembers.value = data.step_ranking || [];
326 + showTotalPointsOnly.value = !data.pending_points?.length;
327 + finalTotalPoints.value = data.family.total_points || 0;
328 + familyName.value = data.family.name;
329 + familySlogn.value = data.family.note;
330 + familyCover.value = data.family.avatar_url || defaultFamilyCover;
331 + familyOwner.value = data.family.is_my;
332 + todaySteps.value = data.my_today_step;
333 + totalFamilySteps.value = data.family_today_step;
334 +
335 + console.log('Dashboard页面数据刷新成功:', {
336 + familyName: familyName.value,
337 + todaySteps: todaySteps.value,
338 + totalPoints: finalTotalPoints.value
339 + });
340 + } else {
341 + console.error('获取Dashboard数据失败:', data);
342 + }
343 + } catch (error) {
344 + console.error('刷新Dashboard数据异常:', error);
345 + }
346 +};
317 347
318 - // 设置页面数据(数据已经在getFamilyDashboardAPI中获取到了) 348 +/**
319 - pendingPoints.value = data.pending_points || []; 349 + * 页面加载时执行静默授权
320 - familyMembers.value = data.step_ranking || []; 350 + */
321 - showTotalPointsOnly.value = !data.pending_points?.length; 351 +useLoad(async () => {
322 - finalTotalPoints.value = data.family.total_points || 0; 352 + console.log('Dashboard页面加载,开始静默授权');
323 - familyName.value = data.family.name; 353 +
324 - familySlogn.value = data.family.note; 354 + // 进行静默授权
325 - familyCover.value = data.family.avatar_url || defaultFamilyCover; 355 + try {
326 - familyOwner.value = data.family.is_my; 356 + await silentAuth(
327 - todaySteps.value = data.my_today_step; 357 + async (result) => {
328 - totalFamilySteps.value = data.family_today_step; 358 + console.log('Dashboard onLoad - 静默授权成功:', result);
359 + // 静默授权成功后立即刷新页面数据
360 + await refreshDashboardData();
361 + },
362 + (error) => {
363 + console.error('Dashboard onLoad - 静默授权失败:', error);
364 + }
365 + );
366 + } catch (error) {
367 + console.error('Dashboard onLoad - 静默授权异常:', error);
368 + }
369 +});
329 370
330 - // 正常刷新微信步数数据 371 +useDidShow(async () => {
331 - if (weRunAuthRef.value) { 372 + // 刷新页面数据
332 - weRunAuthRef.value.checkAuthStatus(true); 373 + await refreshDashboardData();
333 - }
334 374
335 - // 刷新排行榜数据 375 + // 正常刷新微信步数数据
336 - if (rankingCardRef.value) { 376 + if (weRunAuthRef.value) {
337 - rankingCardRef.value.refreshData(); 377 + weRunAuthRef.value.checkAuthStatus(true);
338 - } 378 + }
379 +
380 + // 刷新排行榜数据
381 + if (rankingCardRef.value) {
382 + rankingCardRef.value.refreshData();
339 } 383 }
340 384
341 // TODO: 获取广告信息 385 // TODO: 获取广告信息
......
1 /* 1 /*
2 * @Date: 2025-01-25 10:00:00 2 * @Date: 2025-01-25 10:00:00
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2025-09-12 10:52:09 4 + * @LastEditTime: 2025-09-12 12:24:03
5 * @FilePath: /lls_program/src/utils/authRedirect.js 5 * @FilePath: /lls_program/src/utils/authRedirect.js
6 * @Description: 授权重定向处理工具函数 6 * @Description: 授权重定向处理工具函数
7 */ 7 */
...@@ -209,15 +209,14 @@ export const addShareFlag = (path) => { ...@@ -209,15 +209,14 @@ export const addShareFlag = (path) => {
209 * @returns {Promise} 授权结果 209 * @returns {Promise} 授权结果
210 */ 210 */
211 export const silentAuth = async (onSuccess, onError) => { 211 export const silentAuth = async (onSuccess, onError) => {
212 - return new Promise((resolve, reject) => { 212 + try {
213 // 检查是否已经授权 213 // 检查是否已经授权
214 if (!needAuth()) { 214 if (!needAuth()) {
215 // 已经授权,直接返回成功 215 // 已经授权,直接返回成功
216 if (onSuccess) { 216 if (onSuccess) {
217 onSuccess({ code: 1, msg: '已授权' }) 217 onSuccess({ code: 1, msg: '已授权' })
218 } 218 }
219 - resolve({ code: 1, msg: '已授权' }) 219 + return { code: 1, msg: '已授权' }
220 - return
221 } 220 }
222 221
223 // 显示loading提示 222 // 显示loading提示
...@@ -227,100 +226,106 @@ export const silentAuth = async (onSuccess, onError) => { ...@@ -227,100 +226,106 @@ export const silentAuth = async (onSuccess, onError) => {
227 }) 226 })
228 227
229 // 调用微信登录 228 // 调用微信登录
230 - Taro.login({ 229 + const loginResult = await new Promise((resolve, reject) => {
231 - success: function (res) { 230 + Taro.login({
232 - if (res.code) { 231 + success: resolve,
233 - // 构建请求数据 232 + fail: reject
234 - const requestData = { 233 + })
235 - code: res.code, 234 + })
236 - } 235 +
237 - 236 + if (!loginResult.code) {
238 - // 测试环境下传递openid,正式环境不传递 237 + throw new Error('获取微信登录code失败')
239 - if (process.env.NODE_ENV === 'development') { 238 + }
240 - requestData.openid = 'h-008'; 239 +
241 - // requestData.openid = 'h-009'; 240 + // 构建请求数据
242 - // requestData.openid = 'h-010'; 241 + const requestData = {
243 - // requestData.openid = 'h-011'; 242 + code: loginResult.code,
244 - // requestData.openid = 'h-012'; 243 + }
245 - // requestData.openid = 'h-013'; 244 +
246 - // requestData.openid = 'oWbdFvkD5VtloC50wSNR9IWiU2q8'; 245 + // 测试环境下传递openid,正式环境不传递
247 - // requestData.openid = 'oex8h5QZnZJto3ttvO6swSvylAQo'; 246 + if (process.env.NODE_ENV === 'development') {
248 - } 247 + requestData.openid = 'h-008';
249 - 248 + // requestData.openid = 'h-009';
250 - // 发起授权请求 - 使用request.post保持与手动授权一致 249 + // requestData.openid = 'h-010';
251 - request.post('/srv/?a=openid', requestData) 250 + // requestData.openid = 'h-011';
252 - .then(response => { 251 + // requestData.openid = 'h-012';
253 - Taro.hideLoading() 252 + // requestData.openid = 'h-013';
254 - 253 + // requestData.openid = 'oWbdFvkD5VtloC50wSNR9IWiU2q8';
255 - if (response.data.code) { 254 + // requestData.openid = 'oex8h5QZnZJto3ttvO6swSvylAQo';
256 - const cookie = response.cookies && response.cookies[0] 255 + }
257 - if (cookie) {
258 - // 保存sessionid到本地存储
259 - wx.setStorageSync("sessionid", cookie)
260 -
261 - // 更新request默认headers
262 - request.defaults.headers.cookie = cookie
263 -
264 - // 静默授权成功
265 -
266 - // 执行成功回调
267 - if (onSuccess) {
268 - onSuccess(response.data)
269 - }
270 -
271 - resolve(response.data)
272 - } else {
273 - console.error('授权响应中没有cookie信息')
274 -
275 - if (onError) {
276 - onError('授权失败:没有获取到有效的会话信息')
277 - }
278 -
279 - reject(new Error('授权失败:没有获取到有效的会话信息'))
280 - }
281 - } else {
282 - console.error('静默授权失败:', response.data.msg)
283 -
284 - if (onError) {
285 - onError(response.data.msg || '授权失败')
286 - }
287 -
288 - reject(new Error(response.data.msg || '授权失败'))
289 - }
290 - })
291 - .catch(error => {
292 - console.error('静默授权请求失败:', error)
293 - Taro.hideLoading()
294 -
295 - if (onError) {
296 - onError('网络请求失败,请稍后重试')
297 - }
298 -
299 - reject(new Error('授权失败,请稍后重试'))
300 - })
301 - } else {
302 - console.error('微信登录失败:', res.errMsg)
303 - Taro.hideLoading()
304 -
305 - if (onError) {
306 - onError('微信登录失败:' + res.errMsg)
307 - }
308 -
309 - reject(new Error('微信登录失败:' + res.errMsg))
310 - }
311 - },
312 - fail: (error) => {
313 - console.error('调用微信登录失败:', error)
314 - Taro.hideLoading()
315 256
316 - if (onError) { 257 + // 发起授权请求
317 - onError('调用微信登录失败') 258 + const response = await request.post('/srv/?a=openid', requestData)
259 + Taro.hideLoading()
260 +
261 + if (!response.data.code) {
262 + const errorMsg = response.data.msg || '授权失败'
263 + console.error('静默授权失败:', errorMsg)
264 + if (onError) {
265 + onError(errorMsg)
266 + }
267 + throw new Error(errorMsg)
268 + }
269 +
270 + const cookie = response.cookies && response.cookies[0]
271 + if (!cookie) {
272 + const errorMsg = '授权失败:没有获取到有效的会话信息'
273 + console.error(errorMsg)
274 + if (onError) {
275 + onError(errorMsg)
276 + }
277 + throw new Error(errorMsg)
278 + }
279 +
280 + // 保存sessionid到本地存储
281 + wx.setStorageSync("sessionid", cookie)
282 +
283 + // 更新request默认headers
284 + request.defaults.headers.cookie = cookie
285 +
286 + // 静默授权成功,检查用户是否已加入家庭
287 + try {
288 + const hasFamily = await checkUserHasFamily()
289 +
290 + // 如果用户没有加入家庭,跳转到欢迎页面
291 + if (!hasFamily) {
292 + await Taro.reLaunch({
293 + url: '/pages/Welcome/index'
294 + })
295 +
296 + const result = { ...response.data, redirected: true }
297 + if (onSuccess) {
298 + onSuccess(result)
318 } 299 }
300 + return result
301 + }
319 302
320 - reject(error) 303 + // 用户已有家庭,执行成功回调
304 + if (onSuccess) {
305 + onSuccess(response.data)
321 } 306 }
322 - }) 307 + return response.data
323 - }) 308 +
309 + } catch (familyCheckError) {
310 + console.error('检查家庭状态失败:', familyCheckError)
311 +
312 + // 家庭检查失败,仍然执行成功回调,让页面正常显示
313 + if (onSuccess) {
314 + onSuccess(response.data)
315 + }
316 + return response.data
317 + }
318 +
319 + } catch (error) {
320 + console.error('静默授权过程失败:', error)
321 + Taro.hideLoading()
322 +
323 + const errorMsg = error.message || '授权失败,请稍后重试'
324 + if (onError) {
325 + onError(errorMsg)
326 + }
327 + throw error
328 + }
324 } 329 }
325 330
326 /** 331 /**
......