user-util.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* eslint-disable no-console */
  2. export default {
  3. get user() {
  4. const val = sessionStorage.getItem('user');
  5. if (!val || val == '') return null;
  6. try {
  7. if (val) return JSON.parse(val);
  8. } catch (err) {
  9. console.error(err);
  10. }
  11. return null;
  12. },
  13. set user(userinfo) {
  14. if (!userinfo) {
  15. sessionStorage.removeItem('user');
  16. } else {
  17. sessionStorage.setItem('user', JSON.stringify(userinfo));
  18. }
  19. if (this.unit) {
  20. this.lastUnit = this.unit;
  21. }
  22. },
  23. get token() {
  24. return sessionStorage.getItem('token') || '';
  25. },
  26. get scope() {
  27. return sessionStorage.getItem('x-domain') || '';
  28. },
  29. set token(token) {
  30. if (!token) {
  31. sessionStorage.removeItem('token');
  32. } else {
  33. sessionStorage.setItem('token', token);
  34. }
  35. },
  36. get isGuest() {
  37. return !this.user || this.user.role === 'guest';
  38. },
  39. get unit() {
  40. if (!this.user || this.user.iss !== 'platform') return undefined;
  41. const unit = this.user.sub.split('@', 2)[1] || 'master';
  42. return unit;
  43. },
  44. get platform() {
  45. const unit = this.unit || this.lastUnit;
  46. return unit === 'master' ? 'master' : 'school';
  47. },
  48. set lastUnit(value) {
  49. localStorage.setItem('unit', value);
  50. },
  51. get lastUnit() {
  52. return localStorage.getItem('unit');
  53. },
  54. get roles() {
  55. const val = sessionStorage.getItem('roles');
  56. if (!val) return [];
  57. try {
  58. if (val) return JSON.parse(val);
  59. } catch (err) {
  60. console.error(err);
  61. }
  62. return [];
  63. },
  64. set roles(roles) {
  65. if (!roles) {
  66. sessionStorage.removeItem('roles');
  67. } else {
  68. sessionStorage.setItem('roles', roles && JSON.stringify(roles));
  69. }
  70. },
  71. save({ userinfo, token, roles }) {
  72. this.user = userinfo;
  73. this.token = token;
  74. this.roles = roles || [];
  75. },
  76. };