import { loginAsync, logoutAsync } from '@/api/common' import { TOKEN_KEY } from '@/constants' import { getURLParam, delCookie, isLocalIP } from '@/utils/utils' import bus from 'vue3-eventbus' /** 获取token */ export function getToken() { // 优先取url的token let urlToken = getURLParam('token') // 拿到token后,删除url的token if (urlToken) { clearURLParams() setToken(urlToken) return urlToken } return localStorage.getItem(TOKEN_KEY) || urlToken } /** 根据是否自动登录设置token */ export function setToken(value) { localStorage.setItem(TOKEN_KEY, value) bus.emit('tokenChange', value) } /** 移除登录token */ export function removeToken() { localStorage.removeItem(TOKEN_KEY) } /** 清除url的token参数 */ function clearURLParams() { const stateObject = {} const title = document.title const newUrl = window.location.pathname history.replaceState(stateObject, title, newUrl) } /** 获取本地登录页面path */ export function getLoginPath() { const { origin, pathname } = window.location const path = '/' + pathname.split('/')[1] return (path + '/login').replace('//', '/') } /** 获取登录页面url */ export function getOuterLoginUrl() { const { origin, port, hostname, pathname } = window.location const path = '/' + pathname.split('/')[1] const localUrl = encodeURIComponent(origin + path) if (isLocalIP(hostname) && !hostname.includes('192.168')) { return `http://10.10.8.5:${port}/access/api/v1/idassLogin?sourceUrl=${localUrl}` } else { return origin.replace(port, '32001') + `/access/api/v1/idassLogin?sourceUrl=${localUrl}` } } /** 跳转到登录页面 */ export function navToLogin(redirect?: string) { sessionStorage.clear() localStorage.clear() // token的值就是JSESSIONID delCookie('JSESSIONID') if (redirect) { window.location.href = redirect } else { // 排除localhost if (window.location.hostname === 'localhost') { bus.emit('gotoLogin', '/login') } else { // 跳转到中软的登录页面 window.location.href = getOuterLoginUrl() } // // 直接跳转到登录页 // const url = getLoginPath() // setTimeout(() => { // bus.emit('gotoLogin', '/login') // }) } } /** 退出登录 */ export async function logout() { try { const res = await logoutAsync() navToLogin(res.data || '') } catch (err) { navToLogin() } } /** 登录 */ export async function login(user = { account: '', password: '' }) { const token = getToken() if (token) { setToken(token) return token } else { const { data } = await loginAsync(user) // 触发token变化,Side组件会监听 setToken(data.token) return data.token } }