permission.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress'
  5. import 'nprogress/nprogress.css'
  6. import { getToken } from '@/utils/auth'
  7. import { isRelogin } from '@/utils/request'
  8. import { isPadDevice } from '@/utils/device'; // 设备检测工具函数
  9. NProgress.configure({ showSpinner: false })
  10. const whiteList = ['/login','/loginPad','/user/doLogin', '/auth-redirect', '/bind', '/register','/screen','/pad']
  11. router.beforeEach((to, from, next) => {
  12. NProgress.start()
  13. if (getToken()) {
  14. to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  15. /* has token*/
  16. if (to.path === '/login') {
  17. next({ path: '/index' })
  18. NProgress.done()
  19. }else if (to.path === '/loginPad') {
  20. next({ path: '/pad' })
  21. NProgress.done()
  22. }
  23. else {
  24. if (store.getters.roles.length === 0) {
  25. isRelogin.show = true
  26. // 判断当前用户是否已拉取完user_info信息
  27. store.dispatch('GetInfo').then(() => {
  28. isRelogin.show = false
  29. store.dispatch('GenerateRoutes').then(accessRoutes => {
  30. // 根据roles权限生成可访问的路由表
  31. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  32. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  33. })
  34. }).catch(err => {
  35. store.dispatch('LogOut').then(() => {
  36. const loginPath = isPadDevice() ? 2 : 1;
  37. Message.error(err)
  38. if(loginPath==1){
  39. next({ path: '/login' })
  40. }else{
  41. next({ path: '/loginPad' })
  42. }
  43. })
  44. })
  45. } else {
  46. next()
  47. }
  48. }
  49. } else {
  50. // 没有token
  51. if (whiteList.indexOf(to.path) !== -1) {
  52. // 在免登录白名单,直接进入
  53. next()
  54. } else {
  55. const loginPath = isPadDevice() ? 2 : 1;
  56. // next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  57. if(loginPath==1){
  58. next(`/login`) // 否则全部重定向到登录页
  59. }else{
  60. next(`/pad`) // 否则全部重定向到登录页
  61. }
  62. NProgress.done()
  63. }
  64. }
  65. })
  66. router.afterEach(() => {
  67. NProgress.done()
  68. })