Browse Source

登录逻辑新版

CzRger 1 year ago
parent
commit
3042085ec7

+ 8 - 0
src/api/modules/account.ts

@@ -0,0 +1,8 @@
+import { handle } from '../index'
+
+const suffix = 'api'
+
+export const getUserInfoByUsername = () => handle({
+  url: `/${suffix}/account/search`,
+  method: 'get',
+})

+ 14 - 0
src/api/modules/auth.ts

@@ -0,0 +1,14 @@
+import { handle } from '../index'
+
+const suffix = 'api'
+
+export const login = (params: any) => handle({
+  url: `/${suffix}/auth/login`,
+  method: 'post',
+  params
+})
+
+export const logout = () => handle({
+  url: `/${suffix}/auth/logout`,
+  method: 'get',
+})

+ 5 - 5
src/api/modules/ztpt.ts

@@ -2,7 +2,7 @@ import { handle } from '../index'
 
 const suffix = 'api-ztpt'
 
-export const getLoginCode = (params: any) => handle({
+export const ztptGetLoginCode = (params: any) => handle({
   url: `/${suffix}/api-idaas/validata/code/${params}`,
   method: 'get',
   config: {
@@ -10,23 +10,23 @@ export const getLoginCode = (params: any) => handle({
   }
 })
 
-export const login = (params: any) => handle({
+export const ztptLogin = (params: any) => handle({
   url: `/${suffix}/api-idaas/idaas/sso/login`,
   method: 'post',
   params
 })
 
-export const getUserInfo = () => handle({
+export const ztptGetUserInfo = () => handle({
   url: `/${suffix}/api-idaas/idaas/sso/user/info`,
   method: 'get',
 })
 
-export const getUserRoleList = () => handle({
+export const ztptGetUserRoleList = () => handle({
   url: `/${suffix}/api-idaas/idaas/ps/user/roleList`,
   method: 'get',
 })
 
-export const logout = () => handle({
+export const ztptLogout = () => handle({
   url: `/${suffix}/api-idaas/mq/user/logout`,
   method: 'get',
 })

+ 0 - 3
src/api/request.ts

@@ -26,7 +26,6 @@ export class HttpRequest {
       }
       this.axios.get(paramUrl, {
         headers: {
-          sessionToken: sessionStorage.getItem('sg_token'),
           Authorization: sessionStorage.getItem('sg_token')
         },
         ...config
@@ -41,7 +40,6 @@ export class HttpRequest {
     return new Promise((resolve, reject) => {
       this.axios.post(url, params, {
         headers: {
-          sessionToken: sessionStorage.getItem('sg_token'),
           Authorization: sessionStorage.getItem('sg_token'),
         },
         ...config
@@ -71,7 +69,6 @@ export class HttpRequest {
       }
       this.axios.get(paramUrl, {
         headers: {
-          sessionToken: sessionStorage.getItem('sg_token'),
           Authorization: sessionStorage.getItem('sg_token'),
         },
         responseType: 'arraybuffer',

+ 1 - 2
src/layout/header/head-com.vue

@@ -4,12 +4,11 @@
       <CusEllipsis :value="dutyPeopleCpt"/>
     </div>
     <div class="head-com-right">
-      <el-button @click="$store.commit('app/SET_SWITCH_ZBY')">切换角色</el-button>
       <img class="icon-date" src="@/assets/images/layout/head_icon-1.png">
       <div class="date">{{currentDateCpt}}</div>
       <img class="icon-user" src="@/assets/images/layout/head_icon-2.png">
       <div class="name">{{$store.state.app.userInfo?.displayName}}</div>
-      <div class="dept">{{$store.state.app.userInfo?.organizations?.[0]?.organizationName}}</div>
+      <div class="dept">{{$store.state.app.userInfo?.dept?.organizationName}}</div>
       <div class="button __hover" @click="onLogout">退出</div>
     </div>
   </div>

+ 21 - 16
src/router/index.ts

@@ -3,7 +3,6 @@ import LayoutCom from '@/layout/index.vue'
 import staticRouter from './modules/static'
 import store from '@/store/index'
 import TempCom from '@/views/global/temp.vue'
-import * as api from '@/api/index'
 import RouterViewCom from "@/layout/router-view.vue";
 import {stagingRouterMap, stagingRouter} from './modules/staging'
 import {systemRouterMap, systemRouter} from './modules/system'
@@ -58,10 +57,12 @@ router.beforeEach((to, from , next) => {
 const getInit = (to: any, next: any) => {
     document.title = to?.meta?.title || (import.meta as any).env.VITE_PROJECT_TITLE
     if (to.path === '/') {
-        const firstRoute = store.state.menu.allRouters[0]
-        next({
-            path: firstRoute.redirect || firstRoute.path
-        })
+        const firstRoute = store.state.menu.allRouters?.[0]
+        if (firstRoute) {
+            next({
+                path: firstRoute.redirect || firstRoute.path
+            })
+        }
     } else {
         const m = to.matched[1]?.children?.map((v: any) => {
             v.expend = v.children?.some((s: any) => s.path === to.path)
@@ -82,17 +83,21 @@ const getInit = (to: any, next: any) => {
 export const initMainRouter = async () => {
     if (sessionStorage.getItem("sg_token") && location.pathname !== '/login') {
         store.dispatch('app/LOAD_TIMESTAMP')
-        setRouters()
-        // await Promise.all([
-        //     store.dispatch('app/LOAD_USER_INFO'),
-        // ]).then(async ([{u, r}]) => {
-        //     if (r.some(v => ['ZBY', 'ZBGL'].includes(v.permissionValue))) {
-        //         setRouters()
-        //     } else {
-        //         ElMessage.warning('该账号无系统角色!')
-        //         toLogin()
-        //     }
-        // })
+        await Promise.all([
+            store.dispatch('app/LOAD_USER_INFO'),
+        ]).then(async ([u]) => {
+            if (u.roles.some(v => ['ZBY', 'ZBGL'].includes(v.permissionValue))) {
+                setRouters()
+            } else {
+                ElMessage({
+                    duration: 0,
+                    type: 'warning',
+                    message: '该账号无系统角色!点击关闭按钮跳转到登录页。',
+                    showClose: true,
+                    onClose: () => toLogin()
+                })
+            }
+        })
     }
 
 }

+ 11 - 20
src/store/modules/app.ts

@@ -1,5 +1,6 @@
 import * as api from '@/api/index'
-import {getUserInfo, getUserRoleList} from "@/api/modules/ztpt";
+// import {ztptGetUserInfo, ztptGetUserRoleList} from "@/api/modules/ztpt";
+import {getUserInfoByUsername} from "@/api/modules/account";
 
 const state = {
 	apiProxy: {
@@ -7,14 +8,13 @@ const state = {
 	},
 	userInfo: <any>{},
 	userRoleList: [],
-	zby: true,
 	timestamp: new Date().getTime(),
 	weekStart: 6
 }
 
 const getters = {
 	isZBY: (state) => {
-		return state.zby
+		return state.userRoleList.some(v => v.permissionValue === 'ZBY')
 	},
 	isWeeklyDay: (state) => {
 		return new Date(state.timestamp).getDay() === 5
@@ -22,11 +22,9 @@ const getters = {
 }
 
 const mutations = {
-	SET_USER_INFO(state: any, data: object) {
+	SET_USER_INFO(state: any, data: any) {
 		state.userInfo = data
-	},
-	SET_USER_ROLE(state: any, data: object) {
-		state.userRoleList = data
+		state.userRoleList = data.roles
 	},
 	SET_TIMESTAMP(state: any, data: any) {
 		state.timestamp = new Date(data).getTime()
@@ -34,25 +32,18 @@ const mutations = {
 			state.timestamp += 1000
 		}, 1000)
 	},
-	SET_SWITCH_ZBY(state: any) {
-		state.zby = !state.zby
-	},
 }
 
 const actions = {
 	LOAD_USER_INFO({ commit }: any, refresh: boolean = false) {
 		return new Promise((resolve, reject) => {
-			if (refresh || !state.userInfo?.userId) {
-				Promise.all([
-					getUserInfo(),
-					getUserRoleList()
-				]).then(([u, r]) => {
-					if (u.code === 0 && r.code === 0) {
-						commit('SET_USER_INFO', u.userInfo)
-						commit('SET_USER_ROLE', r.userRoleList)
-						resolve({u: u.userInfo, r: r.userRoleList})
+			if (refresh || !state.userInfo?.id) {
+				getUserInfoByUsername().then((res) => {
+					if (res.code === 200) {
+						commit('SET_USER_INFO', res.data)
+						resolve(res.data)
 					} else {
-						reject(u.msg || r.msg)
+						reject(res.message)
 					}
 				})
 			} else {

+ 35 - 16
src/views/global/login.vue

@@ -16,15 +16,15 @@
             <el-input @keyup.enter="onNormalClick" v-model="form.password" placeholder="输入您的密码" show-password/>
           </el-form-item>
         </div>
-        <div class="code">
-          <el-form-item prop="validCode" :rules="[
-              { required: true, trigger: 'blur', message: '请输入验证码' }]">
-            <el-input @keyup.enter="onNormalClick" v-model="form.validCode" placeholder="验证码"/>
-          </el-form-item>
-          <div class="code-img __hover" @click="initCode" v-loading="loadingCode">
-            <img :src="codeImg"/>
-          </div>
-        </div>
+<!--        <div class="code">-->
+<!--          <el-form-item prop="validCode" :rules="[-->
+<!--              { required: true, trigger: 'blur', message: '请输入验证码' }]">-->
+<!--            <el-input @keyup.enter="onNormalClick" v-model="form.validCode" placeholder="验证码"/>-->
+<!--          </el-form-item>-->
+<!--          <div class="code-img __hover" @click="initCode" v-loading="loadingCode">-->
+<!--            <img :src="codeImg"/>-->
+<!--          </div>-->
+<!--        </div>-->
       </el-form>
       <div class="button __hover" @click="onNormalClick"/>
     </div>
@@ -48,7 +48,6 @@ import {useStore} from 'vuex'
 import {useRouter, useRoute} from 'vue-router'
 import {ElMessage, FormInstance} from "element-plus";
 import { v4 } from "uuid";
-import {getUserRoleList} from "@/api/modules/ztpt";
 export default defineComponent({
   name: '',
   components: {},
@@ -59,19 +58,19 @@ export default defineComponent({
     const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
     const state = reactive({
       form: {
-        deviceId: '',
+        // deviceId: '',
         username: '',
         password: '',
-        validCode: ''
+        // validCode: ''
       },
       codeImg: '',
       loadingCode: false,
       loadingForm: false,
     })
     const ref_form = ref<FormInstance>()
-    const onNormalClick = () => {
-      sessionStorage.setItem('sg_token', '123')
-      location.replace('/')
+    const onZTPTNormalClick = () => {
+      // sessionStorage.setItem('sg_token', '123')
+      // location.replace('/')
 
       if (!ref_form.value) return
       ref_form.value.validate((valid, fields) => {
@@ -104,8 +103,28 @@ export default defineComponent({
         state.loadingCode = false
       })
     }
+    const onNormalClick = () => {
+      if (!ref_form.value) return
+      ref_form.value.validate((valid, fields) => {
+        if (valid) {
+          state.loadingForm = true
+          that.$api.login(state.form).then(res => {
+            if (res.code === 200) {
+              ElMessage.success(res.message)
+              sessionStorage.setItem('sg_token', res.token)
+              location.replace('/')
+            } else {
+              ElMessage.warning(res.message)
+            }
+            state.loadingForm = false
+          }).catch(() => {
+            state.loadingForm = false
+          })
+        }
+      })
+    }
     onMounted(() => {
-      initCode()
+      // initCode()
     })
     return {
       ...toRefs(state),

+ 7 - 0
vite.config.ts

@@ -48,6 +48,13 @@ export default defineConfig({
           return path.replace(/^\/api-ztpt/, '')
         }
       },
+      '/api/': {
+        target: 'http://8.140.240.182:18091/',
+        changeOrigin: true,
+        rewrite: path => {
+          return path.replace(/^\/api/, '')
+        }
+      },
     }
   },
   build: {