Parcourir la source

项目跳转传token并判断跳转

ming il y a 3 ans
Parent
commit
7e276eb00f

+ 3 - 3
public/static/config.js

@@ -1,9 +1,9 @@
 // api 请求路径
 var PLATFROM_CONFIG = {};
-// PLATFROM_CONFIG.baseUrl = "http://172.16.120.104:8010/" //杨强本地
-// PLATFROM_CONFIG.baseUrl = "http://172.16.1.196:8010/"  //超博本地
+PLATFROM_CONFIG.baseUrl = "http://172.16.120.104:8010/" //杨强本地
+    // PLATFROM_CONFIG.baseUrl = "http://172.16.1.196:8010/"  //超博本地
 
-PLATFROM_CONFIG.baseUrl = "https://qhome.usky.cn/fivapi/" //线上
+// PLATFROM_CONFIG.baseUrl = "https://qhome.usky.cn/fivapi/" //线上
 PLATFROM_CONFIG.images = "https://qhome.usky.cn/file/" //线上图片
 PLATFROM_CONFIG.fileUrl = "https://qhome.usky.cn/file/" //xlsx文件访问路径
 

+ 136 - 134
src/store/modules/user.js

@@ -4,153 +4,155 @@
  */
 import { getUserInfo, login, logout } from '@/api/user'
 import {
-  getAccessToken,
-  removeAccessToken,
-  setAccessToken,
+    getAccessToken,
+    removeAccessToken,
+    setAccessToken,
 } from '@/utils/accessToken'
 import { title, tokenName } from '@/config'
 import { message, notification } from 'ant-design-vue'
 
 const state = () => ({
-  accessToken: getAccessToken(),
-  username: '',
-  avatar: '',
+    accessToken: getAccessToken(),
+    username: '',
+    avatar: '',
 })
 const getters = {
-  accessToken: (state) => state.accessToken,
-  username: (state) => state.username,
-  avatar: (state) => state.avatar,
+    accessToken: (state) => state.accessToken,
+    username: (state) => state.username,
+    avatar: (state) => state.avatar,
 }
 const mutations = {
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 设置accessToken
-   * @param {*} state
-   * @param {*} accessToken
-   */
-  setAccessToken(state, accessToken) {
-    state.accessToken = accessToken
-    setAccessToken(accessToken)
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 设置用户名
-   * @param {*} state
-   * @param {*} username
-   */
-  setUsername(state, username) {
-    state.username = username
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 设置头像
-   * @param {*} state
-   * @param {*} avatar
-   */
-  setAvatar(state, avatar) {
-    state.avatar = avatar
-  },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 设置accessToken
+     * @param {*} state
+     * @param {*} accessToken
+     */
+    setAccessToken(state, accessToken) {
+        console.log(state, accessToken)
+        state.accessToken = accessToken
+        setAccessToken(accessToken)
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 设置用户名
+     * @param {*} state
+     * @param {*} username
+     */
+    setUsername(state, username) {
+        state.username = username
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 设置头像
+     * @param {*} state
+     * @param {*} avatar
+     */
+    setAvatar(state, avatar) {
+        state.avatar = avatar
+    },
 }
 const actions = {
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 登录拦截放行时,设置虚拟角色
-   * @param {*} { commit, dispatch }
-   */
-  setVirtualRoles({ commit, dispatch }) {
-    dispatch('acl/setFull', true, { root: true })
-    commit('setAvatar', 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif')
-    commit('setUsername', 'admin(未开启登录拦截)')
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 登录
-   * @param {*} { commit }
-   * @param {*} userInfo
-   */
-  async login({ commit }, userInfo) {
-    const { data } = await login(userInfo)
-    const accessToken = data
-    if (accessToken) {
-      commit('setAccessToken', accessToken)
-      const hour = new Date().getHours()
-      const thisTime =
-        hour < 8
-          ? '早上好'
-          : hour <= 11
-            ? '上午好'
-            : hour <= 13
-              ? '中午好'
-              : hour < 18
-                ? '下午好'
-                : '晚上好'
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 登录拦截放行时,设置虚拟角色
+     * @param {*} { commit, dispatch }
+     */
+    setVirtualRoles({ commit, dispatch }) {
+        dispatch('acl/setFull', true, { root: true })
+        commit('setAvatar', 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif')
+        commit('setUsername', 'admin(未开启登录拦截)')
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 登录
+     * @param {*} { commit }
+     * @param {*} userInfo
+     */
+    async login({ commit }, userInfo) {
+        const { data } = await login(userInfo)
+        const accessToken = data
+        if (accessToken) {
+            commit('setAccessToken', accessToken)
+            const hour = new Date().getHours()
+            const thisTime =
+                hour < 8 ?
+                '早上好' :
+                hour <= 11 ?
+                '上午好' :
+                hour <= 13 ?
+                '中午好' :
+                hour < 18 ?
+                '下午好' :
+                '晚上好'
 
-      title
-      notification.open({
-        // message: `欢迎登录${title}`,
-        message: `登录成功`,
-        description: `${thisTime}!`,
-      })
-    } else {
-      message.error(`登录接口异常,未正确返回${tokenName}...`)
-    }
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 获取用户信息接口 这个接口非常非常重要,如果没有明确底层前逻辑禁止修改此方法,错误的修改可能造成整个框架无法正常使用
-   * @param {*} { commit, dispatch, state }
-   * @returns
-   */
-  async getUserInfo({ commit, dispatch, state }) {
-    const { data } = await getUserInfo(state.accessToken)
+            title
+            notification.open({
+                // message: `欢迎登录${title}`,
+                message: `登录成功`,
+                description: `${thisTime}!`,
+            })
+        } else {
+            message.error(`登录接口异常,未正确返回${tokenName}...`)
+        }
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 获取用户信息接口 这个接口非常非常重要,如果没有明确底层前逻辑禁止修改此方法,错误的修改可能造成整个框架无法正常使用
+     * @param {*} { commit, dispatch, state }
+     * @returns
+     */
+    async getUserInfo({ commit, dispatch, state }) {
+        const { data } = await getUserInfo(state.accessToken)
 
-    if (!data) {
-      message.error(`验证失败,请重新登录...`)
-      return false
-    }
-    // let { username, avatar, roles, ability } = data
-    let { permissions, roles, user, ability } = data
-    permissions
-    let { avatar, userName } = user
+        if (!data) {
+            message.error(`验证失败,请重新登录...`)
+            return false
+        }
+        // let { username, avatar, roles, ability } = data
+        let { permissions, roles, user, ability } = data
+        permissions
+        let { avatar, userName } = user
 
-    if (userName && roles && Array.isArray(roles)) {
-      dispatch('acl/setRole', roles, { root: true })
-      if (ability && ability.length > 0)
-        dispatch('acl/setAbility', ability, { root: true })
-      commit('setUsername', userName)
-      commit('setAvatar', avatar)
-    } else {
-      message.error('用户信息接口异常')
-    }
-  },
+        if (userName && roles && Array.isArray(roles)) {
+            dispatch('acl/setRole', roles, { root: true })
+            if (ability && ability.length > 0)
+                dispatch('acl/setAbility', ability, { root: true })
+            commit('setUsername', userName)
+            commit('setAvatar', avatar)
+        } else {
+            message.error('用户信息接口异常')
+        }
+    },
 
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 退出登录
-   * @param {*} { dispatch }
-   */
-  async logout({ dispatch }) {
-    await logout(state.accessToken)
-    await dispatch('resetAll')
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 重置accessToken、roles、ability、router等
-   * @param {*} { commit, dispatch }
-   */
-  async resetAll({ dispatch }) {
-    await dispatch('setAccessToken', '')
-    await dispatch('acl/setFull', false, { root: true })
-    await dispatch('acl/setRole', [], { root: true })
-    await dispatch('acl/setAbility', [], { root: true })
-    removeAccessToken()
-  },
-  /**
-   * @author chuzhixin 1204505056@qq.com
-   * @description 设置token
-   */
-  setAccessToken({ commit }, accessToken) {
-    commit('setAccessToken', accessToken)
-  },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 退出登录
+     * @param {*} { dispatch }
+     */
+    async logout({ dispatch }) {
+        await logout(state.accessToken)
+        await dispatch('resetAll')
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 重置accessToken、roles、ability、router等
+     * @param {*} { commit, dispatch }
+     */
+    async resetAll({ dispatch }) {
+        await dispatch('setAccessToken', '')
+        await dispatch('acl/setFull', false, { root: true })
+        await dispatch('acl/setRole', [], { root: true })
+        await dispatch('acl/setAbility', [], { root: true })
+        removeAccessToken()
+    },
+    /**
+     * @author chuzhixin 1204505056@qq.com
+     * @description 设置token
+     */
+    setAccessToken({ commit }, accessToken) {
+        console.log("11111111111111111111111", accessToken)
+        commit('setAccessToken', accessToken)
+    },
 }
-export default { state, getters, mutations, actions }
+export default { state, getters, mutations, actions }

+ 80 - 82
src/utils/request.js

@@ -1,11 +1,11 @@
 import axios from 'axios'
 import {
-  // baseURL,
-  contentType,
-  debounce,
-  requestTimeout,
-  successCode,
-  tokenName,
+    // baseURL,
+    contentType,
+    debounce,
+    requestTimeout,
+    successCode,
+    tokenName,
 } from '@/config'
 import store from '@/store'
 import qs from 'qs'
@@ -24,18 +24,18 @@ let loadingInstance
  * @param {*} msg
  */
 const handleCode = (code, msg) => {
-  switch (code) {
-    case 401:
-      message.error(msg || '登录失效')
-      store.dispatch('user/resetAll').catch(() => { })
-      break
-    case 403:
-      router.push({ path: '/401' }).catch(() => { })
-      break
-    default:
-      message.error(msg || `后端接口${code}异常`)
-      break
-  }
+    switch (code) {
+        case 401:
+            message.error(msg || '登录失效')
+            store.dispatch('user/resetAll').catch(() => {})
+            break
+        case 403:
+            router.push({ path: '/401' }).catch(() => {})
+            break
+        default:
+            message.error(msg || `后端接口${code}异常`)
+            break
+    }
 }
 
 /**
@@ -43,13 +43,13 @@ const handleCode = (code, msg) => {
  * @description axios初始化
  */
 const baseURL = window.PLATFROM_CONFIG.baseUrl
-// console.log(baseURL)
+    // console.log(baseURL)
 const instance = axios.create({
-  baseURL,
-  timeout: requestTimeout,
-  headers: {
-    'Content-Type': contentType,
-  },
+    baseURL,
+    timeout: requestTimeout,
+    headers: {
+        'Content-Type': contentType,
+    },
 })
 
 /**
@@ -57,23 +57,23 @@ const instance = axios.create({
  * @description axios请求拦截器
  */
 instance.interceptors.request.use(
-  (config) => {
-    if (store.getters['user/accessToken'])
-      config.headers[tokenName] = store.getters['user/accessToken']
-    if (
-      config.data &&
-      config.headers['Content-Type'] ===
-      'application/x-www-form-urlencoded;charset=UTF-8'
-    )
-      config.data = qs.stringify(config.data)
-    if (debounce.some((item) => config.url.includes(item))) {
-      //这里写加载动画
+    (config) => {
+        if (store.getters['user/accessToken'])
+            config.headers[tokenName] = store.getters['user/accessToken']
+        if (
+            config.data &&
+            config.headers['Content-Type'] ===
+            'application/x-www-form-urlencoded;charset=UTF-8'
+        )
+            config.data = qs.stringify(config.data)
+        if (debounce.some((item) => config.url.includes(item))) {
+            //这里写加载动画
+        }
+        return config
+    },
+    (error) => {
+        return Promise.reject(error)
     }
-    return config
-  },
-  (error) => {
-    return Promise.reject(error)
-  }
 )
 
 /**
@@ -81,50 +81,48 @@ instance.interceptors.request.use(
  * @description axios响应拦截器
  */
 instance.interceptors.response.use(
-  (response) => {
-    if (loadingInstance) loadingInstance.close()
+    (response) => {
+        if (loadingInstance) loadingInstance.close()
 
 
-    const { data, config } = response
-    const { code, msg } = data
-    // 操作正常Code数组
-    const codeVerificationArray = isArray(successCode)
-      ? [...successCode]
-      : [...[successCode]]
-    // 是否操作正常
-    if (codeVerificationArray.includes(parseInt(code))) {
-      return data
-    } else {
-      handleCode(code, msg)
-      return Promise.reject(
-        'vue-admin-beautiful请求异常拦截:' +
-        JSON.stringify({ url: config.url, code, msg }) || 'Error'
-      )
-    }
-  },
-  (error) => {
-    if (loadingInstance) loadingInstance.close()
-    const { response, message } = error
-    if (error.response && error.response.data) {
-      const { status, data } = response
-      handleCode(status, data.msg || message)
-      return Promise.reject(error)
-    } else {
-      let { message } = error
-      if (message === 'Network Error') {
-        message = '后端接口连接异常'
-      }
-      if (message.includes('timeout')) {
-        message = '后端接口请求超时'
-      }
-      if (message.includes('Request failed with status code')) {
-        const code = message.substr(message.length - 3)
-        message = '后端接口' + code + '异常'
-      }
-      message.error(message || `后端接口未知异常`)
-      return Promise.reject(error)
+        const { data, config } = response
+        const { code, msg } = data
+        // 操作正常Code数组
+        const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]]
+            // 是否操作正常
+        if (codeVerificationArray.includes(parseInt(code))) {
+            return data
+        } else {
+            handleCode(code, msg)
+            return Promise.reject(
+                'vue-admin-beautiful请求异常拦截:' +
+                JSON.stringify({ url: config.url, code, msg }) || 'Error'
+            )
+        }
+    },
+    (error) => {
+        if (loadingInstance) loadingInstance.close()
+        const { response, message } = error
+        if (error.response && error.response.data) {
+            const { status, data } = response
+            handleCode(status, data.msg || message)
+            return Promise.reject(error)
+        } else {
+            let { message } = error
+            if (message === 'Network Error') {
+                message = '后端接口连接异常'
+            }
+            if (message.includes('timeout')) {
+                message = '后端接口请求超时'
+            }
+            if (message.includes('Request failed with status code')) {
+                const code = message.substr(message.length - 3)
+                message = '后端接口' + code + '异常'
+            }
+            message.error(message || `后端接口未知异常`)
+            return Promise.reject(error)
+        }
     }
-  }
 )
 
-export default instance
+export default instance

+ 74 - 54
src/vab/plugins/permissions.js

@@ -6,69 +6,89 @@ import router from '@/router'
 import store from '@/store'
 import getPageTitle from '@/utils/pageTitle'
 import {
-  authentication,
-  loginInterception,
-  recordRoute,
-  routesWhiteList,
+    authentication,
+    loginInterception,
+    recordRoute,
+    routesWhiteList,
 } from '@/config'
+import {
+    setAccessToken,
+    getAccessToken,
+} from '@/utils/accessToken'
 
-router.beforeEach(async (to, from, next) => {
-  let hasToken = store.getters['user/accessToken']
+router.beforeEach(async(to, from, next) => {
+    console.log(to)
+    console.log(store)
 
-  if (!loginInterception) hasToken = true
 
-  if (hasToken) {
-    if (to.path === '/login') {
-      next({ path: '/' })
-    } else {
-      const hasRoles =
-        store.getters['acl/admin'] ||
-        store.getters['acl/role'].length > 0 ||
-        store.getters['acl/ability'].length > 0
-      if (hasRoles) {
+
+    if (to.query != undefined && to.query != null) {
+        // store.state.data.user.accessToken = to.query.assToken
+        // store.commit('setAccessToken', to.query.assToken)
+        store.dispatch('setAccessToken', to.query.assToken)
+        setAccessToken(to.query.assToken)
+
+        console.log(getAccessToken())
         next()
-      } else {
-        try {
-          if (loginInterception) {
-            await store.dispatch('user/getUserInfo')
-          } else {
-            //loginInterception为false(关闭登录拦截时)时,创建虚拟角色
-            await store.dispatch('user/setVirtualRoles')
-          }
+    }
+
+    let hasToken = store.getters['user/accessToken']
 
-          let accessRoutes = []
-          if (authentication === 'intelligence') {
-            accessRoutes = await store.dispatch('routes/setRoutes')
-          } else if (authentication === 'all') {
-            accessRoutes = await store.dispatch('routes/setAllRoutes')
-          }
-          accessRoutes.forEach((item) => {
-            router.addRoute(item)
-          })
+    if (!loginInterception) hasToken = true
 
-          next({ ...to, replace: true })
-        } catch {
-          await store.dispatch('user/resetAll')
-          if (recordRoute)
-            next({
-              path: '/login',
-              query: { redirect: to.path },
-              replace: true,
-            })
-          else next({ path: '/login', replace: true })
+    if (hasToken) {
+        // debugger;
+        if (to.path === '/login') {
+            next({ path: '/' })
+        } else {
+            const hasRoles =
+                store.getters['acl/admin'] ||
+                store.getters['acl/role'].length > 0 ||
+                store.getters['acl/ability'].length > 0
+            if (hasRoles) {
+                next()
+            } else {
+                try {
+                    if (loginInterception) {
+                        await store.dispatch('user/getUserInfo')
+                    } else {
+                        //loginInterception为false(关闭登录拦截时)时,创建虚拟角色
+                        await store.dispatch('user/setVirtualRoles')
+                    }
+
+                    let accessRoutes = []
+                    if (authentication === 'intelligence') {
+                        accessRoutes = await store.dispatch('routes/setRoutes')
+                    } else if (authentication === 'all') {
+                        accessRoutes = await store.dispatch('routes/setAllRoutes')
+                    }
+                    accessRoutes.forEach((item) => {
+                        router.addRoute(item)
+                    })
+
+                    next({...to, replace: true })
+                } catch {
+                    await store.dispatch('user/resetAll')
+                    if (recordRoute)
+                        next({
+                            path: '/login',
+                            query: { redirect: to.path },
+                            replace: true,
+                        })
+                    else next({ path: '/login', replace: true })
+                }
+            }
         }
-      }
-    }
-  } else {
-    if (routesWhiteList.indexOf(to.path) !== -1) {
-      next()
     } else {
-      if (recordRoute)
-        next({ path: '/login', query: { redirect: to.path }, replace: true })
-      else next({ path: '/login', replace: true })
+        if (routesWhiteList.indexOf(to.path) !== -1) {
+            next()
+        } else {
+            if (recordRoute)
+                next({ path: '/login', query: { redirect: to.path }, replace: true })
+            else next({ path: '/login', replace: true })
+        }
     }
-  }
 })
 router.afterEach((to) => {
-  document.title = getPageTitle(to.meta.title)
-})
+    document.title = getPageTitle(to.meta.title)
+})

+ 17 - 7
src/views/alarmManage/index.vue

@@ -70,7 +70,7 @@
               width:
                 (scope.row.totalGrade / allMaxData.totalNumMax) * 100 + '%',
             }"
-            @click="goAlarmTotal(0,scope.row.siteName,scope.row.siteId)"
+            @click="goAlarmTotal(0, scope.row.siteName, scope.row.siteId)"
           >
             {{ scope.row.totalGrade }}
           </span>
@@ -85,7 +85,7 @@
               width:
                 (scope.row.oneGrade / allMaxData.oneAlarmingMax) * 100 + '%',
             }"
-            @click="goAlarmTotal(1,scope.row.siteName,scope.row.siteId)"
+            @click="goAlarmTotal(1, scope.row.siteName, scope.row.siteId)"
           >
             {{ scope.row.oneGrade }}
           </span>
@@ -100,7 +100,7 @@
               width:
                 (scope.row.twoGrade / allMaxData.twoAlarmingMax) * 100 + '%',
             }"
-            @click="goAlarmTotal(2,scope.row.siteName,scope.row.siteId)"
+            @click="goAlarmTotal(2, scope.row.siteName, scope.row.siteId)"
           >
             {{ scope.row.twoGrade }}
           </span>
@@ -115,7 +115,7 @@
             :style="{
               width: (scope.row.otherGrade / allMaxData.otherMax) * 100 + '%',
             }"
-            @click="goAlarmTotal(3,scope.row.siteName,scope.row.siteId)"
+            @click="goAlarmTotal(3, scope.row.siteName, scope.row.siteId)"
           >
             {{ scope.row.otherGrade }}
           </span>
@@ -157,6 +157,8 @@ import { computed, defineComponent, onMounted, ref } from 'vue'
 import * as api from '@/api/alarmManage/index'
 import { ElMessage } from 'element-plus'
 import { useRouter } from 'vue-router'
+import { setAccessToken, getAccessToken } from '@/utils/accessToken'
+
 export default defineComponent({
   components: { alarmTotal },
   name: 'VariableList',
@@ -167,7 +169,7 @@ export default defineComponent({
     const pageShow = ref(true)
     const alarmGradeList = ref({})
     // const dateValue = ref([new Date(2020, 10, 10, 10, 10), new Date()])
-     const dateValue = ref('')
+    const dateValue = ref('')
 
     const total = ref(0)
     const pageSize = ref(15)
@@ -209,7 +211,7 @@ export default defineComponent({
       // this.$router.push({ name:'variableList'})
     }
 
-    const goAlarmTotal = (val,val1,val2) => {
+    const goAlarmTotal = (val, val1, val2) => {
       pageShow.value = !pageShow.value
       store.commit('TimeAll_function', dateValue.value)
       if (val != undefined) {
@@ -218,12 +220,20 @@ export default defineComponent({
           endTime: store.state.Time_Data[1],
           type: val,
           siteName: val1,
-          siteId:val2
+          siteId: val2,
         }
       }
     }
 
     onMounted(() => {
+      var aa = router.currentRoute.value.query.assToken
+      // console.log(router.currentRoute.value.query.assToken)
+      setAccessToken(aa)
+      console.log(getAccessToken())
+      router.push({
+        path: '../siteManage/variableList/index.vue',
+      })
+
       listSelect()
       // console.log(store, router)
     })

+ 1 - 1
src/views/siteManage/addSiteCom.vue

@@ -4,7 +4,7 @@
     v-model="dialogVisible"
     @close="closeDialog2('默认关闭')"
     @open="open"
-    width="500px"
+    width="400px"
   >
     <el-form
       ref="formInfo"