Browse Source

fix:登录修改

zhaojing 1 year ago
parent
commit
08de1df1b4

+ 9 - 0
config/proxy.ts

@@ -34,6 +34,15 @@ export default {
         '^/sgadmin/duoduo-service': '/duoduo-service',
       },
     },
+    '/hanchao': {
+      target: 'http://192.168.16.181:52009/',
+      //   target: 'http://10.100.28.79',
+      changeOrigin: true,
+      pathRewrite: {
+        // '^/sgadmin': '/sgadmin',
+        '^/hanchao': '',
+      },
+    },
     '/xiaojing': {
       target: 'http://192.168.4.29:52015/',
       //   target: 'http://10.100.28.79',

+ 9 - 138
src/app.tsx

@@ -1,9 +1,7 @@
 import { PageLoading } from '@ant-design/pro-layout';
 import { history, useModel } from 'umi';
-import { checkToken, reFreshCheckToken } from '@/services/sagacare_service/environment';
 import { projectObj } from '@/config/api.js';
 import UserStorage from '@/config/sagacare/sagacare_user';
-const loginPath = '/noAuth';
 
 /** 获取用户信息比较慢的时候会展示一个 loading */
 export const initialStateConfig = {
@@ -20,54 +18,18 @@ export async function getInitialState(): Promise<{
   //loading?: boolean;
   //fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
 }> {
+  console.log('fsdfsdsdd');
   const { location } = history;
-
-  let access_token: any = location.query.access_token;
-  let refresh_token: any = location.query.refresh_token;
-
-  //如果有值 存起来
-  if (access_token) {
-    localStorage.setItem('access_token', access_token);
-    console.log("localStorage.getItem('access_token')", localStorage.getItem('access_token'));
-  }
-  if (refresh_token) {
-    localStorage.setItem('refresh_token', refresh_token);
+  var token = localStorage.getItem('token');
+  if (location.pathname.indexOf('login') == -1 && !token) {
+    history.push('/login');
   }
-  console.log('getInitialState');
-  //如果没有  取缓存
-  //   if (!refresh_token) {
-  //     refresh_token = localStorage.getItem('refresh_token');
-  //   }
-
-  const fetchUser = async () => {
-    try {
-      access_token = localStorage.getItem('access_token');
-      //if (!access_token) return; //随后去掉
-      //验证acces_token 获取用户数据
-      const res = await checkToken({ token: access_token });
-
-      var resUser = res.data;
-    } catch (err) {
-      history.push(loginPath);
-    }
-
-    if (resUser) {
-      //获取用户信息 并储存
-      var userObj = UserStorage.getInstance();
-      userObj.setUser(resUser);
-
-      return resUser;
-    } else {
-      history.push(loginPath);
-      return undefined;
-    }
-  };
 
   let currentUser = {};
-  //projectId = 'Pj1101080259';
+
   if (projectObj.projectId == 'Pj3301100002') {
     //之江项目 验证token
-    currentUser = await fetchUser();
+    // currentUser = await fetchUser();
   } else {
     //非之江项目
     let tempUser = {
@@ -80,44 +42,6 @@ export async function getInitialState(): Promise<{
     userObj.setUser(tempUser);
   }
 
-  const reFreshUser = async () => {
-    refresh_token = localStorage.getItem('refresh_token');
-    //刷新token 续约token
-    const res = await reFreshCheckToken({
-      zjfreshtoken: refresh_token,
-    });
-    if (res.refresh_token) {
-      console.log('refresh_token', res.refresh_token);
-      localStorage.setItem('refresh_token', res.refresh_token);
-      localStorage.setItem('access_token', res.access_token);
-    } else {
-      //如果刷新token失败
-      //history.push(loginPath);
-    }
-    //1分钟后再执行
-    setTimeout(() => {
-      // reFreshUser();
-    }, 60000);
-  };
-
-  //await reFreshUser();
-
-  // || {
-  //   companyId: '245e7060643811eb934c0237aedb39a6',
-  //   createDate: 1642388952000,
-  //   depName: '[["研发算法组","上格云","博锐尚格科技股份有限公司"]]',
-  //   firstUseTime: '2020-10-16 18:37:05',
-  //   id: '2d2440710d4548f3afa55c4e8244538e',
-  //   job: '研发工程师',
-  //   manageUserType: 1,
-  //   name: '赵小静',
-  //   phone: '18801040736',
-  //   projectId: 'Pj1101080259',
-  //   status: 2,
-  //   type: 1,
-  //   updateDate: 1642388952000,
-  // };
-
   return {
     currentUser,
     fetchUser,
@@ -132,6 +56,9 @@ export const request = {
         options: {
           ...options,
           interceptors: true,
+          headers: {
+            'saga-token': localStorage.getItem('token'),
+          },
         },
       };
     },
@@ -149,59 +76,3 @@ export const request = {
     throw error;
   },
 };
-
-// ProLayout 支持的api https://procomponents.ant.design/components/layout
-// export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
-//   return {
-//     rightContentRender: () => <RightContent />,
-//     disableContentMargin: false,
-//     waterMarkProps: {
-//       content: initialState?.currentUser?.name,
-//     },
-//     footerRender: () => <Footer />,
-//     onPageChange: () => {
-//       const { location } = history;
-//       // 如果没有登录,重定向到 login
-//       if (!initialState?.currentUser && location.pathname !== loginPath) {
-//         history.push(loginPath);
-//       }
-//     },
-//     links: isDev
-//       ? [
-//           <Link to="/umi/plugin/openapi" target="_blank">
-//             <LinkOutlined />
-//             <span>OpenAPI 文档</span>
-//           </Link>,
-//           <Link to="/~docs">
-//             <BookOutlined />
-//             <span>业务组件文档</span>
-//           </Link>,
-//         ]
-//       : [],
-//     menuHeaderRender: undefined,
-//     // 自定义 403 页面
-//     // unAccessible: <div>unAccessible</div>,
-//     // 增加一个 loading 的状态
-//     childrenRender: (children, props) => {
-//       // if (initialState?.loading) return <PageLoading />;
-//       return (
-//         <>
-//           {children}
-//           {!props.location?.pathname?.includes('/login') && (
-//             <SettingDrawer
-//               enableDarkTheme
-//               settings={initialState?.settings}
-//               onSettingChange={(settings) => {
-//                 setInitialState((preInitialState) => ({
-//                   ...preInitialState,
-//                   settings,
-//                 }));
-//               }}
-//             />
-//           )}
-//         </>
-//       );
-//     },
-//     ...initialState?.settings,
-//   };
-// };

+ 106 - 0
src/pages/Login/index.jsx

@@ -0,0 +1,106 @@
+import React, { useState, useEffect, useCallback, useRef } from 'react';
+import { FormattedMessage, history, useModel } from 'umi';
+import styles from './index.less';
+import cx from 'classnames';
+import QRCode from 'qrcodejs2';
+import { qrCodeInfo } from '@/services/sagacare_service/member';
+import { ReloadOutlined } from '@ant-design/icons';
+
+export default () => {
+  const loginLogo = require('@/assets/images/loginLogo.svg');
+  const qrcodeRef = useRef();
+  const wsRef = useRef();
+  const [expireTime, setExpireTime] = useState(); //过期时间
+  const [qrCodeId, setQrCodeId] = useState(); //生成二维码id
+
+  const getqrCodeInfo = () => {
+    qrCodeInfo()
+      .then((res) => {
+        var expireTime = res?.data?.expireTime;
+        var qrCodeId = res?.data?.qrCodeId;
+        setExpireTime(expireTime);
+        setQrCodeId(qrCodeId);
+      })
+      .catch((err) => {});
+  };
+
+  useEffect(() => {
+    getqrCodeInfo();
+  }, []);
+
+  useEffect(() => {
+    if (!qrCodeId) return;
+    if (qrcodeRef.current) {
+      qrcodeRef.current.makeCode(qrCodeId);
+    } else {
+      qrcodeRef.current = new QRCode('qrcodeRef', {
+        text: qrCodeId,
+        width: 160,
+        height: 160,
+        colorDark: '#000000',
+        colorLight: '#ffffff',
+      });
+    }
+
+    wsRef.current = new WebSocket(
+      `wss://duoduoenv.sagacloud.cn/duoduo-service/duoduoenv-service/webSocket/${qrCodeId}`,
+    );
+    // 获取连接状态
+    console.log('ws连接状态:' + wsRef.current.readyState);
+    //监听是否连接成功
+    wsRef.current.onopen = function () {
+      console.log('ws连接状态:onopen' + wsRef.current.readyState);
+      //连接成功则发送一个数据
+      //  wsRef.current.send('test1');
+    };
+    // 接听服务器发回的信息并处理展示
+    wsRef.current.onmessage = function (data) {
+      console.log('接收到来自服务器的消息:', data.data);
+      if (data?.data?.indexOf('token') > -1) {
+        var info = JSON.parse(data.data);
+        console.log('登录成功:', info);
+        var userInfo = info.tokenUser;
+        var token = info.token;
+        localStorage.setItem('userInfo', userInfo);
+        localStorage.setItem('token', token);
+        history.push('/home');
+      }
+      //完成通信后关闭WebSocket连接
+      //  wsRef.current.close();
+    };
+    // 监听连接关闭事件
+    wsRef.current.onclose = function (e) {
+      // 监听整个过程中websocket的状态
+      console.log('ws连接状态:onclose' + wsRef.current.readyState);
+      console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
+    };
+    // 监听并处理error事件
+    wsRef.current.onerror = function (error) {
+      console.log('ws连接状态:error', error);
+    };
+  }, [qrCodeId]);
+
+  const reloadQrcode = () => {
+    getqrCodeInfo();
+  };
+
+  return (
+    <div className={styles.loginWrap}>
+      <div className={styles.loginBox}>
+        <div className={styles.image}>
+          <img src={loginLogo} style={{ height: 110 }}></img>
+        </div>
+        <div className={styles.qrcodeWrap}>
+          {expireTime < new Date().getTime() && (
+            <div className={styles.qrCover}>
+              <ReloadOutlined style={{ fontSize: '25px' }} onClick={reloadQrcode} />
+            </div>
+          )}
+
+          <div className={styles.qrcode} id="qrcodeRef"></div>
+        </div>
+        <div className={styles.info}>请使用小程序扫码登录</div>
+      </div>
+    </div>
+  );
+};

+ 22 - 0
src/pages/Login/index.less

@@ -16,10 +16,32 @@
       text-align: center;
     }
     .info {
+      margin-top: 24px;
       color: #1b2129;
       font-size: 16px;
       line-height: 24px;
       text-align: center;
     }
+    .qrcodeWrap {
+      position: relative;
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      .qrcode {
+        width: 160px;
+      }
+      .qrCover {
+        position: absolute;
+        top: 0;
+        right: 0;
+        left: 0;
+        display: flex;
+        align-items: center;
+        justify-content: center;
+        // width: 160px;
+        height: 160px;
+        background-color: rgba(255, 255, 255, 0.8);
+      }
+    }
   }
 }

+ 0 - 20
src/pages/Login/index.tsx

@@ -1,20 +0,0 @@
-import React, { useState, useEffect, useCallback, useRef } from 'react';
-import { FormattedMessage, history, useModel } from 'umi';
-import { Spin, Popover } from 'antd';
-import styles from './index.less';
-import cx from 'classnames';
-
-export default () => {
-  const loginLogo = require('@/assets/images/loginLogo.svg');
-  return (
-    <div className={styles.loginWrap}>
-      <div className={styles.loginBox}>
-        <div className={styles.image}>
-          <img src={loginLogo} style={{ height: 110 }}></img>
-        </div>
-        <div className={styles.qrcode}></div>
-        <div className={styles.info}>请使用小程序扫码登录</div>
-      </div>
-    </div>
-  );
-};

+ 6 - 4
src/pages/Member/components/personModal/index.jsx

@@ -82,13 +82,15 @@ const PersonModal = ({
       .validateFields()
       .then((value) => {
         //处理可控工区
-        var slist = checkedValues.map((item) => {
+        var slist = [];
+        checkedValues.forEach((item) => {
           if (item != 'special') {
-            return {
+            slist.push({
               companyId: 'ff80c708fe72446eb790b764c3a7b66b',
               spaceId: item,
               isPermanentSpace: radioValue == item ? true : false,
-            };
+              userId: checkUser.userId,
+            });
           }
         });
 
@@ -135,7 +137,7 @@ const PersonModal = ({
     3: '临时成员',
   };
   const invalidPerson = () => {
-    debugger;
+    //填写的用户名不对
     if (nameVal !== checkUser.name) return;
     deleteUser({ userId: checkUser.userId })
       .then((res) => {

+ 13 - 0
src/services/sagacare_service/member.js

@@ -91,3 +91,16 @@ export async function queryCompanyOAById(params, options) {
     ...(options || {}),
   });
 }
+
+//获取二维码信息
+export async function qrCodeInfo(params, options) {
+  // /sgadmin/duoduo-service/duoduoenv-service/userNew/qrCodeInfo
+  return request(`/sgadmin/duoduo-service/duoduoenv-service/userNew/qrCodeInfo`, {
+    method: 'GET',
+    from: 'sagacare',
+    headers: {
+      'Content-Type': 'application/json',
+    },
+    ...(options || {}),
+  });
+}