Explorar el Código

优化微信自动登录

“shengjie.huang” hace 1 año
padre
commit
0931bbe7ea
Se han modificado 6 ficheros con 56 adiciones y 32 borrados
  1. 5 0
      src/App.vue
  2. 0 9
      src/pages/index/index.vue
  3. 4 0
      src/pages/login/index.vue
  4. 3 15
      src/pages/personal/index.vue
  5. 31 2
      src/store/user.ts
  6. 13 6
      src/utils/http.ts

+ 5 - 0
src/App.vue

@@ -1,8 +1,13 @@
 <script setup lang="ts">
 import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
+import { useUserStore } from '@/store'
 
 onLaunch(() => {
   console.log('App Launch')
+  // 已经有登录过token的情况下, 更新token
+  if (useUserStore().isLogined) {
+    useUserStore().wxLogin().then((token) => { })
+  }
 })
 onShow(() => {
   console.log('App Show')

+ 0 - 9
src/pages/index/index.vue

@@ -123,15 +123,6 @@ function initSwiperList() {
   ]
 }
 
-// 跳转
-// uni.reLaunch({
-//   url: `/pages/personal/index`,
-// })
-// uni.navigateTo({
-//   url: `/pages/map/index`,
-// })
-// redirectTo
-
 function toUserHub() {
   if (isLogined.value) {
     uni.navigateTo({

+ 4 - 0
src/pages/login/index.vue

@@ -73,6 +73,10 @@ async function init() {
 }
 
 function handleToken(token) {
+  // 测试过期token
+  // token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im94ckFQNWJyTUNYc0dCb0RQazFGcjlTVHJaQ0EiLCJleHAiOjE3NDA3NDY3MzcsImlhdCI6MTc0MDczOTUzN30.781buxRJuOPaunWYiyHlW0Pam-EZCNuR8ndrRwSuop0"
+  // useUserStore().setToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im94ckFQNWJyTUNYc0dCb0RQazFGcjlTVHJaQ0EiLCJleHAiOjE3NDA3NDY3MzcsImlhdCI6MTc0MDczOTUzN30.781buxRJuOPaunWYiyHlW0Pam-EZCNuR8ndrRwSuop0")
+
   if (token) {
     toast.success("登录成功")
     useUserStore().setToken(token)

+ 3 - 15
src/pages/personal/index.vue

@@ -17,8 +17,7 @@
         :height="40"
         :src="userInfo.avatar"
       />
-      <view class="head-name">{{ isLogined ? userName : "请登录" }}</view>
-      <!-- <view class="head-name">{{ userInfo.name }}</view> -->
+      <view class="head-name">{{ isLogined ? userInfo.name : "请登录" }}</view>
     </view>
     <view class="main-content mt6">
       <!-- <view class="content-item line-b" @click="toTest">
@@ -59,7 +58,6 @@ const userInfo = reactive({
 })
 const toast = useToast()
 const isLogined = computed(() => !!useUserStore().token)
-const userName = computed(() => useUserStore().userInfo?.name || "微信用户")
 
 function toAddUserHub() {
   if (isLogined.value) {
@@ -84,25 +82,15 @@ function toJob() {
 }
 
 function handleLogout() {
-  // logout().then((res) => {
-  //   if (res.code === 0) {
-  //     useUserStore().setToken('')
-  //     useUserStore().setAvatar('')
-  //     useUserStore().setUserInfo({})
-  //     toast.success('退出登录成功')
-  //     toLogin()
-  //   }
-  // })
   useUserStore().clearUserInfo()
   toast.success('退出登录成功')
   toLoginWait(1500)
 }
 
 function initFn() {
-  // userInfo.name = useUserStore().userInfo.name
-  // userInfo.avatar = useUserStore().userInfo.avatar
-  userInfo.name = "微信用户"
+  userInfo.name = useUserStore().userInfo?.name || "微信用户"
   userInfo.avatar = "/static/images/avatar.png"
+  // userInfo.avatar = useUserStore().userInfo.avatar
 }
 
 function toTest() {

+ 31 - 2
src/store/user.ts

@@ -1,6 +1,7 @@
 import { defineStore } from 'pinia'
 import { ref } from 'vue'
-import { getUserInfo } from '@/service/api/index'
+import { loginByCode, getUserInfo } from '@/service/api/index'
+import { getLoginCode } from '@/utils'
 
 const initState = { nickname: '', avatar: '' }
 
@@ -32,6 +33,33 @@ export const useUserStore = defineStore(
     }
     const isLogined = computed(() => !!token.value)
 
+    // 自动登录 (静默登录, 自动更新token, 成功不进行跳转, 返回promise给页面增加逻辑)
+    async function wxLogin() {
+      const code = await getLoginCode()
+      return new Promise<void>((resolve, reject) => {
+        loginByCode({ code })
+          .then((res: any) => {
+            if (res.code === 0) {
+              const accessToken = res.body.token || ''
+              setToken(accessToken)
+              initUserInfo()
+              resolve(accessToken)
+            } else {
+              uni.reLaunch({
+                url: `/pages/login/index?isLogout=1`,
+              })
+              reject(res)
+            }
+          })
+          .catch((error) => {
+            uni.reLaunch({
+              url: `/pages/login/index?isLogout=1`,
+            })
+            reject(error)
+          })
+      })
+    }
+
     async function initUserInfo() {
       // 查询个人信息
       const res: any = await getUserInfo()
@@ -52,7 +80,8 @@ export const useUserStore = defineStore(
       reset,
       setToken,
       setAvatar,
-      initUserInfo
+      initUserInfo,
+      wxLogin,
     }
   },
   {

+ 13 - 6
src/utils/http.ts

@@ -4,7 +4,7 @@ import { useUserStore } from '@/store'
 export const http = <T>(options: CustomRequestOptions) => {
   // 1. 返回 Promise 对象
   return new Promise<IResData<T>>((resolve, reject) => {
-    uni.request({
+    let temp = {
       ...options,
       dataType: 'json',
       // #ifndef MP-WEIXIN
@@ -17,10 +17,16 @@ export const http = <T>(options: CustomRequestOptions) => {
           // 2.1 提取核心数据 res.data
           resolve(res.data as IResData<T>)
         } else if (res.statusCode === 401) {
-          // 401错误  -> 清理用户信息,跳转到登录页
-          useUserStore().clearUserInfo()
-          uni.reLaunch({ url: '/pages/login/index?isLogout=1' })
-          reject(res)
+          // // 401错误 -> 清理用户信息,跳转到登录页
+          // useUserStore().clearUserInfo()
+          // uni.reLaunch({ url: '/pages/login/index?isLogout=1' })
+          // reject(res)
+
+          // 401错误 -> 自动刷新token
+          useUserStore().wxLogin().then((token) => {
+            temp.header['X-ACCESS-TOKEN'] = token
+            uni.request(temp)
+          })
         } else {
           // 其他错误 -> 根据后端错误信息轻提示
           !options.hideErrorToast &&
@@ -42,7 +48,8 @@ export const http = <T>(options: CustomRequestOptions) => {
         }
         reject(err)
       },
-    })
+    }
+    uni.request(temp)
   })
 }