authority.js 2.55 KB
Newer Older
1
import RenderAuthorize from '@/components/Authorized/index.jsx';
2
import { isDev } from './tools.ts';
3
// const isDev = false;
4
let auth = [];
5 6
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-mutable-exports */
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// 获取url地址参数
const getQueryVariable = name => {
  // 获取url上的参数(使用decodeURIComponent对url参数进行解码)
  let search = decodeURIComponent(window.location.search).replace('?', '');
  const tempArr = search !== '' ? search.split('&') : [];

  // 将参数名转小写,参数值保留原大小写
  tempArr.forEach(item => {
    if (item) {
      const itemArr = item.split('=');
      search = search.replace(itemArr[0], itemArr[0].toLowerCase());
    }
  });

  // 正则匹配指定的参数
  const reg = new RegExp(`(^|&)${name.toLowerCase()}=([^&]*)(&|$)`);
  const result = search.match(reg);

  return result != null ? result[2] : '';
};
console.log(getAuthority(), 'getAuthority()');
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
let Authorized = RenderAuthorize(getAuthority());

// Reload the rights component
const reloadAuthorized = () => {
  Authorized = RenderAuthorize(getAuthority());
};

/**
 * hard code
 * block need it。
 */
window.reloadAuthorized = reloadAuthorized;

export { reloadAuthorized };
export default Authorized;

// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str) {
46
  const isSandBox = getQueryVariable('sandbox');
47
  const sandbox = sessionStorage.getItem('_omsticket');
48 49
  if (!isDev) {
    // return [...auth];
50

51
    // 支持可以指直接访问
52 53 54 55 56
    // if (isSandBox == 'true') {
    //   sessionStorage.setItem('_omsticket', 'd438aaf9578f405299ae740c4eb75aae');
    //   return ['LOGIN', 'admin'];
    // }
    if (sandbox == 'd438aaf9578f405299ae740c4eb75aae') {
57 58
      return ['LOGIN', 'admin'];
    }
59
    return [...auth];
60
  }
61
  const authorityString =
62
    typeof str === 'undefined' && localStorage ? localStorage.getItem('panda-oms-authority') : str;
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  // authorityString could be admin, "admin", ["admin"]
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }

  return authority;
}

export function setAuthority(authority) {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
81 82 83
  if (isDev) {
    localStorage.setItem('panda-oms-authority', JSON.stringify(proAuthority));
  } else {
84
    auth = proAuthority;
85
  }
86 87 88
  // auto reload
  reloadAuthorized();
}