| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- import router from './router'
- import type { RouteRecordRaw } from 'vue-router'
- import { isRelogin } from '@/config/axios/service'
- import { getAccessToken } from '@/utils/auth'
- import { useTitle } from '@/hooks/web/useTitle'
- import { useNProgress } from '@/hooks/web/useNProgress'
- import { usePageLoading } from '@/hooks/web/usePageLoading'
- import { useDictStoreWithOut } from '@/store/modules/dict'
- import { useUserStoreWithOut } from '@/store/modules/user'
- import { usePermissionStoreWithOut } from '@/store/modules/permission'
- import * as authUtil from '@/utils/auth'
- const { start, done } = useNProgress()
- const { loadStart, loadDone } = usePageLoading()
- const loading = ref() // ElLoading.service 返回的实例
- const parseURL = (
- url: string | null | undefined
- ): { basePath: string; paramsObject: { [key: string]: string } } => {
- // 如果输入为 null 或 undefined,返回空字符串和空对象
- if (url == null) {
- return { basePath: '', paramsObject: {} }
- }
- // 找到问号 (?) 的位置,它之前是基础路径,之后是查询参数
- const questionMarkIndex = url.indexOf('?')
- let basePath = url
- const paramsObject: { [key: string]: string } = {}
- // 如果找到了问号,说明有查询参数
- if (questionMarkIndex !== -1) {
- // 获取 basePath
- basePath = url.substring(0, questionMarkIndex)
- // 从 URL 中获取查询字符串部分
- const queryString = url.substring(questionMarkIndex + 1)
- // 使用 URLSearchParams 遍历参数
- const searchParams = new URLSearchParams(queryString)
- searchParams.forEach((value, key) => {
- // 封装进 paramsObject 对象
- paramsObject[key] = value
- })
- }
- // 返回 basePath 和 paramsObject
- return { basePath, paramsObject }
- }
- // 单点登录token验证函数
- const validateAndLogin = async () => {
- try {
- const userStore = useUserStoreWithOut()
- // 调用单点登录接口,传入外部token
- // 这里根据你的实际接口调整
- const response = await userStore.ssoLogin()
- // const response = {
- // accessToken: "41f636cc7ff247129e4d4f205bc3a096",
- // expiresTime: 1767094239442,
- // loginType: "cas",
- // refreshToken: "d86a7e71e34b464a898fe2a2e838e572",
- // userId: "140"
- // }
- if (response && response.accessToken) {
- loading.value = ElLoading.service({
- lock: true,
- text: '正在加载系统中...',
- background: 'rgba(0, 0, 0, 0.7)'
- })
- authUtil.setToken(response)
- }
- console.log(response, 'response的数据啊')
-
- // 或者直接调用API
- // import { ssoLoginApi } from '@/api/login'
- // const response = await ssoLoginApi({ token, loginType })
-
- // 保存本系统的token
- // if (response && response.token) {
- // setToken(response.token)
- // return true
- // }
- return true
- } catch (error) {
- console.error('SSO登录失败:', error)
- return false
- }
- }
- // 路由不重定向白名单
- const whiteList = [
- '/login',
- '/social-login',
- '/auth-redirect',
- '/bind',
- '/register',
- '/oauthLogin/gitee'
- ]
- // 路由加载前
- // 路由加载前
- router.beforeEach(async (to, from, next) => {
- start()
- loadStart()
-
- const loginType = to.query.loginType as string
- // 处理单点登录
- if (loginType == 'cas') {
- console.log('检测到SSO登录参数:', loginType )
-
- try {
- // 验证token并登录
- const loginSuccess = await validateAndLogin()
- console.log('SSO登录结果:', loginSuccess)
- if (loginSuccess) {
- // 登录成功,清除URL中的token参数
- const targetPath = to.path === '/' ? '/index' : to.path
- console.log('登录成功,跳转到:', targetPath)
- // 获取用户信息和权限
- const userStore = useUserStoreWithOut()
- const permissionStore = usePermissionStoreWithOut()
- const dictStore = useDictStoreWithOut()
-
- isRelogin.show = true
-
- // 加载字典
- if (!dictStore.getIsSetDict) {
- await dictStore.setDictMap()
- }
-
- // 加载用户信息
- await userStore.setUserInfoAction()
-
- // 加载菜单权限
- await permissionStore.generateRoutes()
- permissionStore.getAddRouters.forEach((route) => {
- router.addRoute(route as unknown as RouteRecordRaw)
- })
- loading.value.close()
- isRelogin.show = false
-
- // 跳转到目标页面,移除token参数
- next({
- path: targetPath,
- query: {},
- replace: true
- })
- } else {
- // token验证失败
- console.log('SSO token验证失败')
- loading.value.close()
- next('/login')
- }
- } catch (error) {
- console.error('SSO登录异常:', error)
- isRelogin.show = false
- next('/login')
- }
- return
- }
- // 正常的登录验证逻辑
- if (getAccessToken()) {
- if (to.path === '/login') {
- next({ path: '/' })
- } else {
- const dictStore = useDictStoreWithOut()
- const userStore = useUserStoreWithOut()
- const permissionStore = usePermissionStoreWithOut()
-
- if (!dictStore.getIsSetDict) {
- await dictStore.setDictMap()
- }
-
- if (!userStore.getIsSetUser) {
- isRelogin.show = true
- await userStore.setUserInfoAction()
- isRelogin.show = false
-
- await permissionStore.generateRoutes()
- permissionStore.getAddRouters.forEach((route) => {
- router.addRoute(route as unknown as RouteRecordRaw)
- })
-
- const redirectPath = from.query.redirect || to.path
- const redirect = decodeURIComponent(redirectPath as string)
- const { paramsObject: query } = parseURL(redirect)
- const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect, query }
- next(nextData)
- } else {
- next()
- }
- }
- } else {
- if (whiteList.indexOf(to.path) !== -1) {
- next()
- } else {
- next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
- }
- }
- })
- router.afterEach((to) => {
- useTitle(to?.meta?.title as string)
- done() // 结束Progress
- loadDone()
- })
|