routeGuard.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { useAuthStore } from '@/store/modules/auth';
  2. interface RouteGuardOptions {
  3. requireAuth?: boolean;
  4. redirectUrl?: string;
  5. }
  6. /**
  7. * 路由守卫 - 检查登录状态
  8. */
  9. export const checkAuth = async (options: RouteGuardOptions = {}): Promise<boolean> => {
  10. const { requireAuth = true, redirectUrl = '/pages/login/login' } = options;
  11. if (!requireAuth) {
  12. return true;
  13. }
  14. const authStore = useAuthStore();
  15. console.log(authStore,"authStore");
  16. // 如果没有token,直接跳转到登录页
  17. if (!authStore.token) {
  18. uni.reLaunch({
  19. url: redirectUrl
  20. });
  21. return false;
  22. }
  23. // 检查token有效性
  24. try {
  25. const isValid = await authStore.checkToken();
  26. if (!isValid) {
  27. uni.reLaunch({
  28. url: redirectUrl
  29. });
  30. return false;
  31. }
  32. return true;
  33. } catch (error) {
  34. console.error('Token check failed:', error);
  35. uni.reLaunch({
  36. url: redirectUrl
  37. });
  38. return false;
  39. }
  40. };
  41. /**
  42. * 页面跳转前的路由守卫
  43. */
  44. export const routeGuard = async (url: string, options: RouteGuardOptions = {}): Promise<void> => {
  45. const isAuthenticated = await checkAuth(options);
  46. console.log(isAuthenticated,'isAuthenticated');
  47. if (isAuthenticated) {
  48. uni.navigateTo({
  49. url
  50. });
  51. }
  52. };
  53. /**
  54. * 带认证检查的页面跳转
  55. */
  56. export const navigateWithAuth = (url: string, options: RouteGuardOptions = {}): void => {
  57. routeGuard(url, options);
  58. };
  59. /**
  60. * 自动登录检查
  61. */
  62. export const autoLogin = async (): Promise<boolean> => {
  63. const authStore = useAuthStore();
  64. console.log(authStore,'自动登录检查');
  65. if (!authStore.token) {
  66. return false;
  67. }
  68. try {
  69. const isValid = await authStore.checkToken();
  70. return isValid;
  71. } catch (error) {
  72. console.error('Auto login failed:', error);
  73. return false;
  74. }
  75. };
  76. /**
  77. * 登出并跳转到登录页
  78. */
  79. export const logoutAndRedirect = async (redirectUrl: string = '/pages/login/login'): Promise<void> => {
  80. const authStore = useAuthStore();
  81. await authStore.logout();
  82. console.log('登出并跳转到登录页');
  83. uni.reLaunch({
  84. url: redirectUrl
  85. });
  86. };