2026-07-14 15:39:19 +08:00
|
|
|
import { useAuthStore } from '@/stores/auth'
|
|
|
|
|
import { authApi } from '@/api/auth'
|
2026-07-15 14:47:42 +08:00
|
|
|
import { redirectToSSO } from '@/utils/sso'
|
2026-07-14 15:39:19 +08:00
|
|
|
|
|
|
|
|
export function useAuth() {
|
|
|
|
|
const authStore = useAuthStore()
|
|
|
|
|
|
|
|
|
|
const login = async (username: string, password: string) => {
|
|
|
|
|
const response = await authApi.login({ username, password })
|
|
|
|
|
const { token, user } = response.data
|
|
|
|
|
authStore.setAuth(token, user)
|
|
|
|
|
return response
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const logout = async () => {
|
2026-07-16 15:52:56 +08:00
|
|
|
try {
|
|
|
|
|
await authApi.logout()
|
|
|
|
|
} finally {
|
|
|
|
|
authStore.clearAuth()
|
|
|
|
|
window.location.assign('/login?logged_out=1')
|
|
|
|
|
}
|
2026-07-14 15:39:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const checkAuth = () => {
|
|
|
|
|
if (!authStore.isLoggedIn()) {
|
2026-07-15 14:47:42 +08:00
|
|
|
redirectToSSO()
|
2026-07-14 15:39:19 +08:00
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
login,
|
|
|
|
|
logout,
|
|
|
|
|
checkAuth,
|
|
|
|
|
}
|
|
|
|
|
}
|