Przeglądaj źródła

登录加上【标准】登录类型

yuhan 7 miesięcy temu
rodzic
commit
883f4e33e8
5 zmienionych plików z 355 dodań i 80 usunięć
  1. 15 5
      src/api/login.js
  2. 118 54
      src/permission.js
  3. 37 6
      src/store/modules/user.js
  4. 24 15
      src/views/user/Login.vue
  5. 161 0
      src/views/user/LoginSSO.vue

+ 15 - 5
src/api/login.js

@@ -14,7 +14,19 @@ import { axios } from '@/utils/request'
  */
 export function login(parameter) {
   return axios({
-    // url: '/sys/login',
+    url: '/sys/login',
+    // url: '/sso/dy/login',
+    method: 'post',
+    data: parameter
+  })
+}
+
+/**
+ * iot-sso账号密码登录
+ * @returns {*}
+ */
+export function iotSsoLogin(parameter) {
+  return axios({
     url: '/sso/dy/login',
     method: 'post',
     data: parameter
@@ -76,12 +88,10 @@ export function thirdLogin(token,thirdType) {
 }
 
 /**
- * iot-sso登录
- * @param eiToken
- * @param username
+ * iot-sso跳转判断EIToken+登录
  * @returns {*}
  */
-export function iotSsoLogin() {
+export function tzLogin() {
   return axios({
     url: `/sso/dy/tzlogin`,
     method: 'post',

+ 118 - 54
src/permission.js

@@ -32,69 +32,133 @@ router.beforeEach((to, from, next) => {
   // param.username = 'iotedge@iotedge.sense'
   // param.token = cookie.get('EIToken')
   // param.username = cookie.get('WISEUser')
-  store.dispatch('IotSsoLogin').then(response => {
-    // 有EIToken
-    // console.log('pppppppppresult', response)
-    if (to.path === '/user/login' || to.path === OAUTH2_LOGIN_PAGE_PATH) {
-      next({ path: INDEX_MAIN_PAGE_PATH })
-      NProgress.done()
-    } else {
-      if (store.getters.permissionList.length === 0) {
-        store.dispatch('GetPermissionList').then(res => {
-          const menuData = res.result.menu;
-          //console.log(res.message)
-          if (menuData === null || menuData === "" || menuData === undefined) {
-            return;
-          }
-          let constRoutes = [];
-          constRoutes = generateIndexRouter(menuData);
-          // 添加主界面路由
-          store.dispatch('UpdateAppRouter',  { constRoutes }).then(() => {
-            // 根据roles权限生成可访问的路由表
-            // 动态添加可访问路由表
-            router.addRoutes(store.getters.addRouters)
-            const redirect = decodeURIComponent(from.query.redirect || to.path)
-            if (to.path === redirect) {
-              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
-              next({ ...to, replace: true })
-            } else {
-              // 跳转到目的路由
-              next({ path: redirect })
+  var loginType = cookie.get('NameType')
+  if(loginType === 'SSO'){
+    store.dispatch('TzLogin').then(response => {
+      // 有EIToken
+      // console.log('pppppppppresult', response)
+      if (to.path === '/user/login' || to.path === OAUTH2_LOGIN_PAGE_PATH) {
+        next({ path: INDEX_MAIN_PAGE_PATH })
+        NProgress.done()
+      } else {
+        if (store.getters.permissionList.length === 0) {
+          store.dispatch('GetPermissionList').then(res => {
+            const menuData = res.result.menu;
+            //console.log(res.message)
+            if (menuData === null || menuData === "" || menuData === undefined) {
+              return;
             }
+            let constRoutes = [];
+            constRoutes = generateIndexRouter(menuData);
+            // 添加主界面路由
+            store.dispatch('UpdateAppRouter',  { constRoutes }).then(() => {
+              // 根据roles权限生成可访问的路由表
+              // 动态添加可访问路由表
+              router.addRoutes(store.getters.addRouters)
+              const redirect = decodeURIComponent(from.query.redirect || to.path)
+              if (to.path === redirect) {
+                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
+                next({ ...to, replace: true })
+              } else {
+                // 跳转到目的路由
+                next({ path: redirect })
+              }
+            })
           })
-        })
-        .catch(() => {
-          /* notification.error({
-            message: '系统提示',
-            description: '请求用户信息失败,请重试!'
-          })*/
-          store.dispatch('Logout').then(() => {
-            next({ path: '/user/login', query: { redirect: to.fullPath } })
+          .catch(() => {
+            /* notification.error({
+              message: '系统提示',
+              description: '请求用户信息失败,请重试!'
+            })*/
+            store.dispatch('Logout').then(() => {
+              next({ path: '/user/login', query: { redirect: to.fullPath } })
+            })
           })
-        })
+        } else {
+          next()
+        }
+      }
+    })
+    .catch(() => {
+      // 没有EIToken-判断有没有token
+      if (whiteList.indexOf(to.path) !== -1) {
+        // 在免登录白名单,如果进入的页面是login页面并且当前是OAuth2app环境,就进入OAuth2登录页面
+        if (to.path === '/user/login' && isOAuth2AppEnv()) {
+          next({path: OAUTH2_LOGIN_PAGE_PATH})
+        } else {
+          // 在免登录白名单,直接进入
+          next()
+        }
+        NProgress.done()
       } else {
-        next()
+        // 如果当前是在OAuth2APP环境,就跳转到OAuth2登录页面
+        let path = isOAuth2AppEnv() ? OAUTH2_LOGIN_PAGE_PATH : '/user/login'
+        next({ path: path, query: { redirect: to.fullPath } })
+        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
       }
-    }
-  })
-  .catch(() => {
-    // 没有EIToken-判断有没有token
-    if (whiteList.indexOf(to.path) !== -1) {
-      // 在免登录白名单,如果进入的页面是login页面并且当前是OAuth2app环境,就进入OAuth2登录页面
-      if (to.path === '/user/login' && isOAuth2AppEnv()) {
-        next({path: OAUTH2_LOGIN_PAGE_PATH})
+    })
+  } else {
+    if (Vue.ls.get(ACCESS_TOKEN)) {
+      /* has token */
+      if (to.path === '/user/login' || to.path === OAUTH2_LOGIN_PAGE_PATH) {
+        next({ path: INDEX_MAIN_PAGE_PATH })
+        NProgress.done()
       } else {
-        // 在免登录白名单,直接进入
-        next()
+        if (store.getters.permissionList.length === 0) {
+          store.dispatch('GetPermissionList').then(res => {
+                const menuData = res.result.menu;
+                //console.log(res.message)
+                if (menuData === null || menuData === "" || menuData === undefined) {
+                  return;
+                }
+                let constRoutes = [];
+                constRoutes = generateIndexRouter(menuData);
+                // 添加主界面路由
+                store.dispatch('UpdateAppRouter',  { constRoutes }).then(() => {
+                  // 根据roles权限生成可访问的路由表
+                  // 动态添加可访问路由表
+                  router.addRoutes(store.getters.addRouters)
+                  const redirect = decodeURIComponent(from.query.redirect || to.path)
+                  if (to.path === redirect) {
+                    // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
+                    next({ ...to, replace: true })
+                  } else {
+                    // 跳转到目的路由
+                    next({ path: redirect })
+                  }
+                })
+              })
+            .catch(() => {
+             /* notification.error({
+                message: '系统提示',
+                description: '请求用户信息失败,请重试!'
+              })*/
+              store.dispatch('Logout').then(() => {
+                next({ path: '/user/login', query: { redirect: to.fullPath } })
+              })
+            })
+        } else {
+          next()
+        }
       }
-      NProgress.done()
     } else {
-      // 如果当前是在OAuth2APP环境,就跳转到OAuth2登录页面
-      let path = isOAuth2AppEnv() ? OAUTH2_LOGIN_PAGE_PATH : '/user/login'
-      next({ path: path, query: { redirect: to.fullPath } })
-      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
+      if (whiteList.indexOf(to.path) !== -1) {
+        // 在免登录白名单,如果进入的页面是login页面并且当前是OAuth2app环境,就进入OAuth2登录页面
+        if (to.path === '/user/login' && isOAuth2AppEnv()) {
+          next({path: OAUTH2_LOGIN_PAGE_PATH})
+        } else {
+          // 在免登录白名单,直接进入
+          next()
+        }
+        NProgress.done()
+      } else {
+        // 如果当前是在OAuth2APP环境,就跳转到OAuth2登录页面
+        let path = isOAuth2AppEnv() ? OAUTH2_LOGIN_PAGE_PATH : '/user/login'
+        next({ path: path, query: { redirect: to.fullPath } })
+        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
+      }
     }
-  })
+  }
 })
 
 router.afterEach(() => {

+ 37 - 6
src/store/modules/user.js

@@ -1,5 +1,5 @@
 import Vue from 'vue'
-import { login, logout, phoneLogin, thirdLogin, iotSsoLogin } from "@/api/login"
+import { login, logout, phoneLogin, thirdLogin, iotSsoLogin, tzLogin } from "@/api/login"
 import { ACCESS_TOKEN, USER_NAME,USER_INFO,USER_AUTH,SYS_BUTTON_AUTH,UI_CACHE_DB_DICT_DATA,TENANT_ID,CACHE_INCLUDED_ROUTES } from "@/store/mutation-types"
 import { welcome } from "@/utils/util"
 import { queryPermissionsByUser } from '@/api/api'
@@ -91,6 +91,9 @@ const user = {
             commit('SET_INFO', userInfo)
             commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
             commit('SET_AVATAR', userInfo.avatar)
+
+            cookie.set('NameType', 'SYSTEM')
+
             resolve(response)
           }else{
             reject(response)
@@ -193,8 +196,9 @@ const user = {
             let serviceUrl = encodeURIComponent(sevice)
             window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
           }
-          // 删除EIToken
-          cookie.remove('EIToken')
+          // 删除登录账号类型
+          // cookie.remove('EIToken')
+          cookie.remove('NameType')
           resolve()
         }).catch(() => {
           resolve()
@@ -226,10 +230,37 @@ const user = {
     },
     // IoT Edge相关 修改框架
     // iot EIToken登录
-    IotSsoLogin({ commit }) {
+    IotSsoLogin({ commit }, userInfo) {
+      return new Promise((resolve, reject) => {
+        iotSsoLogin(userInfo).then(response => {
+          if(response.code =='200'){
+            const result = response.result
+            const userInfo = result.userInfo
+            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
+            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
+            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
+            Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
+            commit('SET_TOKEN', result.token)
+            commit('SET_INFO', userInfo)
+            commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
+            commit('SET_AVATAR', userInfo.avatar)
+
+            cookie.set('NameType', 'SSO')
+
+            resolve(response)
+          }else{
+            reject(response)
+          }
+        }).catch(error => {
+          // console.log('error', error)
+          reject(error)
+        })
+      })
+    },
+    // 跳转EIToken判断+登录
+    TzLogin({ commit }) {
       return new Promise((resolve, reject) => {
-        iotSsoLogin().then(response => {
-          // console.log('IotSsoLogin', response)
+        tzLogin().then(response => {
           if(response.result.code =='200'){
             if(response.update){
               // 更新数据

+ 24 - 15
src/views/user/Login.vue

@@ -3,8 +3,11 @@
     <div class="top-img"></div>
     <div class="sign-text">登录到 联锁管理平台</div>
     <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
-      <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"  @change="handleTabClick" class="login-tabs">
-        <a-tab-pane key="tab1" tab="SSO">
+      <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"  @change="handleTabClick" class="u-login-tabs">
+        <a-tab-pane key="SSO" tab="SSO">
+          <login-sso ref="ssologin" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-sso>
+        </a-tab-pane>
+        <a-tab-pane key="SYSTEM" tab="标准">
           <login-account ref="alogin" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-account>
         </a-tab-pane>
 
@@ -49,7 +52,8 @@ import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
 import { timeFix } from '@/utils/util'
 
 import LoginAccount from './LoginAccount'
-import LoginPhone from './LoginPhone'
+import LoginSso from './LoginSSO'
+// import LoginPhone from './LoginPhone'
 
 export default {
     components: {
@@ -57,11 +61,12 @@ export default {
       TwoStepCaptcha,
       ThirdLogin,
       LoginAccount,
-      LoginPhone
+      LoginSso,
+      // LoginPhone
     },
     data () {
       return {
-        customActiveKey: 'tab1',
+        customActiveKey: 'SSO',
         rememberMe: true,
         loginBtn: false,
         requiredTwoStepCaptcha: false,
@@ -97,12 +102,12 @@ export default {
       //登录
       handleSubmit () {
         this.loginBtn = true;
-        if (this.customActiveKey === 'tab1') {
+        if (this.customActiveKey === 'SSO') {
+          //SSO单点登录
+          this.$refs.ssologin.handleLogin(this.rememberMe)
+        } else {
           // 使用账户密码登录
           this.$refs.alogin.handleLogin(this.rememberMe)
-        } else {
-          //手机号码登录
-          this.$refs.plogin.handleLogin(this.rememberMe)
         }
       },
       // 校验失败
@@ -122,9 +127,9 @@ export default {
           duration: 4,
         });
         //账户密码登录错误后更新验证码
-        if(this.customActiveKey === 'tab1' && description.indexOf('密码错误')>0){
-          this.$refs.alogin.handleChangeCheckCode()
-        }
+        // if(this.customActiveKey === 'SSO' && description.indexOf('密码错误')>0){
+        //   this.$refs.alogin.handleChangeCheckCode()
+        // }
         this.loginBtn = false;
       },
       loginSelectOk(){
@@ -168,18 +173,22 @@ export default {
   }
 </script>
 <style lang="less">
-  .login-tabs{
+  .u-login-tabs{
     .ant-tabs-nav-container{
       font-size: 16px !important;
     }
     .ant-tabs-nav{
-      width: 50%;
+      width: 100%;
+      .ant-tabs-tab{
+        width: 50%;
+        margin: 0;
+      }
     }
     .ant-tabs-nav .ant-tabs-tab-active{
       color: #3395ff !important;
     }
     .ant-tabs-ink-bar{
-      width: 100% !important;
+      width: 50% !important;
       height: 3px;
       background: #3395ff;
     }

+ 161 - 0
src/views/user/LoginSSO.vue

@@ -0,0 +1,161 @@
+<template>
+    <div>
+      <a-form-model ref="form" :model="model" :rules="validatorRules">
+        <!-- IoT Edge相关 修改框架 -->
+        <a-form-model-item required prop="username">
+          <a-input v-model="model.username" size="large" placeholder="请输入帐户名">
+            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
+          </a-input>
+        </a-form-model-item>
+        <a-form-model-item required prop="password">
+          <a-input-password v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码">
+            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
+          </a-input-password>
+        </a-form-model-item>
+
+        <!-- IoT Edge相关 修改框架 -->
+        <!-- <a-row :gutter="0">
+          <a-col :span="16">
+            <a-form-model-item required prop="inputCode">
+              <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码">
+                <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
+              </a-input>
+            </a-form-model-item>
+          </a-col>
+          <a-col :span="8" style="text-align: right">
+            <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
+            <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
+          </a-col>
+        </a-row> -->
+      </a-form-model>
+    </div>
+</template>
+
+<script>
+  import { getAction } from '@/api/manage'
+  import Vue from 'vue'
+  import { mapActions } from 'vuex'
+
+  export default {
+    name: 'LoginAccount',
+    data(){
+      return {
+        requestCodeSuccess: false,
+        randCodeImage: '',
+        currdatetime: '',
+        loginType: 0,
+        model:{
+          username: '',
+          password: '',
+          inputCode: ''
+        },
+        validatorRules:{
+          username: [
+            { required: true, message: '请输入用户名!' },
+            { validator: this.handleUsernameOrEmail }
+          ],
+          password: [{
+            required: true, message: '请输入密码!', validator: 'click'
+          }],
+          inputCode: [{
+            required: true, message: '请输入验证码!'
+          }]
+        }
+
+      }
+    },
+    created() {
+      this.handleChangeCheckCode();
+    },
+    methods:{
+      ...mapActions(['IotSsoLogin']),
+      /**刷新验证码*/
+      handleChangeCheckCode(){
+        this.currdatetime = new Date().getTime();
+        this.model.inputCode = ''
+        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
+          if(res.success){
+            this.randCodeImage = res.result
+            this.requestCodeSuccess=true
+          }else{
+            this.$message.error(res.message)
+            this.requestCodeSuccess=false
+          }
+        }).catch(()=>{
+          this.requestCodeSuccess=false
+        })
+      },
+      // 判断登录类型
+      handleUsernameOrEmail (rule, value, callback) {
+        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
+        if (regex.test(value)) {
+          this.loginType = 0
+        } else {
+          this.loginType = 1
+        }
+        callback()
+      },
+      /**
+       * 验证字段
+       * @param arr
+       * @param callback
+       */
+      validateFields(arr, callback){
+        let promiseArray = []
+        for(let item of arr){
+          let p = new Promise((resolve, reject) => {
+            this.$refs['form'].validateField(item, (err)=>{
+              if(!err){
+                resolve();
+              }else{
+                reject(err);
+              }
+            })
+          });
+          promiseArray.push(p)
+        }
+        Promise.all(promiseArray).then(()=>{
+          callback()
+        }).catch(err=>{
+          callback(err)
+        })
+      },
+      acceptUsername(username){
+        this.model['username'] = username
+      },
+      //账号密码登录
+      handleLogin(rememberMe){
+        this.validateFields([ 'username', 'password' ], (err)=>{
+          if(!err){
+            let loginParams = {
+              username: this.model.username,
+              password: this.model.password,
+              // captcha: this.model.inputCode,
+              checkKey: this.currdatetime,
+              remember_me: rememberMe,
+            }
+            console.log("登录参数", loginParams)
+            this.IotSsoLogin(loginParams).then((res) => {
+              this.$emit('success', res.result)
+            }).catch((err) => {
+              //update-begin-author: taoyan date:20220425 for: 登录页面,当输入验证码错误时,验证码图片要刷新一下,而不是保持旧的验证码图片不变 #41
+              // if(err && err.code===412){
+              //   this.handleChangeCheckCode();
+              // }
+              //update-end-author: taoyan date:20220425 for: 登录页面,当输入验证码错误时,验证码图片要刷新一下,而不是保持旧的验证码图片不变 #41
+              this.$emit('fail', err)
+            });
+          }else{
+            this.$emit('validateFail')
+          }
+        })
+      }
+
+
+    }
+
+  }
+</script>
+
+<style>
+</style>