CheckLogin.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import React from 'react';
  2. import Redirect from 'umi/redirect';
  3. import { apiUrl } from '@/utils/sldconfig';
  4. export default ({ children }) => {
  5. let cur_time = new Date().getTime();
  6. let start_time = localStorage.getItem('time');
  7. if (typeof start_time == 'undefined' || start_time == null) {
  8. return <Redirect to="/user/login"/>;
  9. } else {
  10. if (cur_time - start_time > 58 * 60 * 1000) {
  11. //用户token过期之后重新根据refresh_token获取token(58分钟,token的有效期是60分钟)
  12. let param = new FormData();
  13. param.append('grant_type', 'refresh_token');
  14. param.append('refresh_token', localStorage.getItem('sld_refresh_token'));
  15. fetch(apiUrl + 'v3/adminLogin/oauth/token', {
  16. credentials: 'include',
  17. headers: {
  18. Authorization: 'Basic YWRtaW46YWRtaW4=',
  19. },
  20. method: 'POST',
  21. body: param,
  22. }).then(response => response.json())
  23. .then(res => {
  24. if (res.state == 200) {
  25. localStorage.setItem('sld_token', res.data.access_token);
  26. localStorage.setItem('sld_refresh_token', res.data.refresh_token);
  27. } else {
  28. return <Redirect to="/user/login"/>;
  29. }
  30. });
  31. } else if (cur_time - start_time > ((24 * 60 * 15 - 2) * 60 * 1000)) {
  32. //用户登陆过期之后直接跳转登录页面(14天23小时58分钟,refresh_token的有效期是15天)
  33. return <Redirect to="/user/login"/>;
  34. }
  35. }
  36. //如果redirect在用户拥有的路由内,则跳转,否则跳转第一个页面
  37. if (localStorage.sld_all_routes != undefined) {
  38. let all_routes = JSON.parse(localStorage.sld_all_routes);
  39. let contain_redirect_flag = false;
  40. for (let i = 0; i < all_routes.length; i++) {
  41. if (children.props.location.pathname.indexOf("/manage_product/") >-1 || children.props.location.pathname.indexOf(all_routes[i]) > -1) {
  42. contain_redirect_flag = true;
  43. break;
  44. }
  45. }
  46. if (!contain_redirect_flag) {
  47. return <Redirect to={all_routes[0]}/>;
  48. }
  49. }
  50. return children;
  51. };