Просмотр исходного кода

refactor(auth): 移除token认证逻辑并重构用户登录流程

- 删除auth.ts及相关token管理函数
- 修改登录接口和用户信息获取接口,不再依赖token
- 使用uni-app存储替代cookie存储用户信息
- 重构微信登录流程,简化参数传递
- 更新用户头像默认路径为新增的default-avatar.png
- 在个人中心页面增加登录状态判断和登录按钮
```

这个提交消息遵循了以下原则:
1. 使用refactor类型,因为这是对现有代码结构的重构
2. 添加了scope(auth)来明确这是认证相关的重构
3. 描述简明扼要地说明了主要变更
4. 在body中列出了主要变更点,没有重复描述
5. 使用中文并保持简洁,每个变更点用短句说明
6. 使用动词开头并保持一致的格式
feige996 11 месяцев назад
Родитель
Сommit
b4316befdd

+ 4 - 7
src/api/login.ts

@@ -30,8 +30,8 @@ export const login = (loginForm: ILoginForm) => {
 /**
  * 获取用户信息
  */
-export const getUserInfo = (token: string) => {
-  return http.get<IUserInfoVo>('/user/info', { token })
+export const getUserInfo = () => {
+  return http.get<IUserInfoVo>('/user/info')
 }
 
 /**
@@ -72,15 +72,12 @@ export const getWxCode = () => {
 /**
  * 微信登录参数
  */
-export interface IWxLoginParams {
-  code: string
-}
 
 /**
  * 微信登录
  * @param params 微信登录参数,包含code
  * @returns Promise 包含登录结果
  */
-export const wxLogin = (params: IWxLoginParams) => {
-  return http.post<IUserLogin>('/app/wx/login', {}, params)
+export const wxLogin = (data: { code: string }) => {
+  return http.post<IUserLogin>('/user/wxLogin', data)
 }

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

@@ -127,7 +127,7 @@
 import { ref } from 'vue'
 import { useUserStore } from '@/store/user'
 import { isMpWeixin } from '@/utils/platform'
-import { getCode, getWxCode, ILoginForm } from '@/api/login'
+import { getCode, ILoginForm } from '@/api/login'
 import { toast } from '@/utils/toast'
 import { isTableBar } from '@/utils/index'
 import { ICaptcha } from '@/api/login.typings'
@@ -210,10 +210,8 @@ const handleWechatLogin = async () => {
     toast.error('请先阅读并同意用户协议和隐私政策')
     return
   }
-  // 获取微信小程序登录的code
-  const { code } = await getWxCode()
   // 微信登录
-  await userStore.wxLogin({ code })
+  await userStore.wxLogin()
   // 获取用户信息
   await userStore.getUserInfo()
   // 跳转到首页或重定向页面

+ 26 - 4
src/pages/mine/index.vue

@@ -77,7 +77,8 @@
       </view>
 
       <view class="logout-button-wrapper">
-        <wd-button type="error" block @click="handleLogout">退出登录</wd-button>
+        <wd-button type="error" v-if="hasLogin" block @click="handleLogout">退出登录</wd-button>
+        <wd-button type="primary" v-else block @click="handleLogin">登录</wd-button>
       </view>
     </view>
   </view>
@@ -90,10 +91,16 @@ import { uploadFileUrl, useUpload } from '@/utils/uploadFile'
 import { storeToRefs } from 'pinia'
 import { IUploadSuccessInfo } from '@/api/login.typings'
 
+const userStore = useUserStore()
+
 const toast = useToast()
+const hasLogin = ref(false)
+
 onShow((options) => {
+  hasLogin.value = !!uni.getStorageSync('token')
   console.log('个人中心onShow', options)
-  useUserStore().getUserInfo()
+
+  hasLogin.value && useUserStore().getUserInfo()
 })
 // #ifndef MP-WEIXIN
 // 上传头像
@@ -106,7 +113,21 @@ const { run } = useUpload<IUploadSuccessInfo>(
 )
 // #endif
 
+// 微信小程序下登录
+const handleLogin = async () => {
+  // #ifdef MP-WEIXIN
+
+  // 微信登录
+  await userStore.wxLogin()
+  hasLogin.value = true
+  // #endif
+  // #ifndef MP-WEIXIN
+  uni.navigateTo({ url: '/pages/login/index' })
+  // #endif
+}
+
 // #ifdef MP-WEIXIN
+
 // 微信小程序下选择头像事件
 const onChooseAvatar = (e: any) => {
   console.log('选择头像', e.detail)
@@ -215,15 +236,16 @@ const handleLogout = () => {
       if (res.confirm) {
         // 清空用户信息
         useUserStore().logout()
+        hasLogin.value = false
         // 执行退出登录逻辑
         toast.success('退出登录成功')
         // #ifdef MP-WEIXIN
         // 微信小程序,去首页
-        uni.reLaunch({ url: '/pages/index/index' })
+        // uni.reLaunch({ url: '/pages/index/index' })
         // #endif
         // #ifndef MP-WEIXIN
         // 非微信小程序,去登录页
-        uni.reLaunch({ url: '/pages/login/index' })
+        // uni.reLaunch({ url: '/pages/login/index' })
         // #endif
       }
     },

BIN
src/static/images/default-avatar.png


+ 17 - 9
src/store/user.ts

@@ -3,8 +3,8 @@ import {
   getUserInfo as _getUserInfo,
   wxLogin as _wxLogin,
   logout as _logout,
+  getWxCode,
 } from '@/api/login'
-import { getToken, getTokenKey, removeToken, setToken } from '@/utils/auth'
 import { defineStore } from 'pinia'
 import { ref } from 'vue'
 import { toast } from '@/utils/toast'
@@ -18,7 +18,7 @@ const userInfoState: IUserInfoVo = {
   sex: '',
   email: '',
   phone: '',
-  avatar: '/static/images/avatar.jpg',
+  avatar: '/static/images/default-avatar.png',
   createTime: '',
   roles: [],
   permissions: [],
@@ -43,7 +43,8 @@ export const useUserStore = defineStore(
     // 删除用户信息
     const removeUserInfo = () => {
       userInfo.value = { ...userInfoState }
-      removeToken()
+      uni.removeStorageSync('userInfo')
+      uni.removeStorageSync('token')
     }
     /**
      * 用户登录
@@ -59,14 +60,16 @@ export const useUserStore = defineStore(
       const res = await _login(credentials)
       console.log('登录信息', res)
       toast.success('登录成功')
-      setToken(res.data.token)
+      const userInfo = res.data
+      uni.setStorageSync('userInfo', userInfo)
+      uni.setStorageSync('token', userInfo.token)
       return res
     }
     /**
      * 获取用户信息
      */
     const getUserInfo = async () => {
-      const res = await _getUserInfo(getToken())
+      const res = await _getUserInfo()
       setUserInfo(res.data)
       // TODO 这里可以增加获取用户路由的方法 根据用户的角色动态生成路由
       return res
@@ -80,11 +83,16 @@ export const useUserStore = defineStore(
     }
     /**
      * 微信登录
-     * @param credentials 微信登录Code
      */
-    const wxLogin = async (credentials: { code: string }) => {
-      const res = await _wxLogin(credentials)
-      setToken(res.data.token)
+    const wxLogin = async () => {
+      // 获取微信小程序登录的code
+      const data = await getWxCode()
+      console.log('微信登录code', data)
+
+      const res = await _wxLogin(data)
+      const userInfo = res.data
+      uni.setStorageSync('userInfo', userInfo)
+      uni.setStorageSync('token', userInfo.token)
       return res
     }
 

+ 0 - 81
src/utils/auth.ts

@@ -1,81 +0,0 @@
-import Cookie from 'js-cookie'
-import { isMpWeixin } from './platform'
-/**
- * TokeKey的名字
- */
-const TokenKey: string = 'token'
-
-/**
- * 获取tokenKeyName
- * @returns tokenKeyName
- */
-export const getTokenKey = (): string => {
-  return TokenKey
-}
-
-/**
- * 是否登录,即是否有token,不检查Token是否过期和是否有效
- * @returns 是否登录
- */
-export const isLogin = () => {
-  return !!getToken()
-}
-
-/**
- * 获取Token
- * @returns 令牌
- */
-export const getToken = () => {
-  return getCookieMap<string>(getTokenKey())
-}
-
-/**
- * 设置Token
- * @param token 令牌
- */
-export const setToken = (token: string) => {
-  setCookieMap(getTokenKey(), token)
-}
-/**
- * 删除Token
- */
-export const removeToken = () => {
-  removeCookieMap(getTokenKey())
-}
-
-/**
- * 设置Cookie
- * @param key Cookie的key
- * @param value Cookie的value
- */
-export const setCookieMap = (key: string, value: any) => {
-  if (isMpWeixin) {
-    uni.setStorageSync(key, value)
-    return
-  }
-  Cookie.set(key, value)
-}
-
-/**
- * 获取Cookie
- * @param key Cookie的key
- * @returns Cookie的value
- */
-export const getCookieMap = <T>(key: string) => {
-  if (isMpWeixin) {
-    return uni.getStorageSync(key) as T
-  }
-  return Cookie.get(key) as T
-}
-
-/**
- * 删除Cookie
- * @param key Cookie的key
- */
-export const removeCookieMap = (key: string) => {
-  if (isMpWeixin) {
-    uni.removeStorageSync(key)
-    return
-  }
-  Cookie.remove(key)
-}

+ 0 - 2
src/utils/uploadFile.ts

@@ -1,4 +1,3 @@
-import { getToken, getTokenKey } from './auth'
 import { toast } from './toast'
 
 /**
@@ -286,7 +285,6 @@ function uploadFile<T>({
         // #ifndef H5
         'Content-Type': 'multipart/form-data',
         // #endif
-        [getTokenKey()]: getToken(), // 添加认证token
       },
       // 确保文件名称合法
       success: (uploadFileRes) => {