import type { AuthcClient } from 'authc-spa-js' import createAuthcClient from 'authc-spa-js' import { computed, ref, watch } from 'vue' import { useRoute, useRouter } from 'vue-router' import { useMessage } from 'naive-ui' const useAuthc = () => { const isLogin = ref(false) const authc = ref(null) const tKey = computed(() => authc.value?.tk) const userInfo = ref() const router = useRouter() const route = useRoute() const message = useMessage() const updateInfo = async () => { userInfo.value = await authc.value!.getIdTokenClaims() } const checkLogin = (loading?: any, tk?: boolean) => { authc.value?.isAuthenticated().then(async (status) => { if (!status) return router.replace('/') isLogin.value = true updateInfo() if (tk) await tKey.value?.triggerLogin() loading?.destroy() }) } const handleRedirectCallback = () => { if (route.query.code && route.query.state) { const loading = message.loading('login~~~') authc.value?.handleRedirectCallback().then(() => { checkLogin(loading, true) }) } } watch(route, () => { handleRedirectCallback() }, { immediate: true, }) createAuthcClient({ domain: 'auth-stage.ucollex.io', client_id: '95f15921-52f4-47dc-985b-d50ecf7cddcc', useRefreshTokens: true, cacheLocation: 'localstorage', advancedOptions: { defaultScope: 'openid profile email phone', }, tkOptions: { verifier: 'authc-verifier2', directParams: { baseUrl: '.', }, }, }).then((instance) => { authc.value = instance checkLogin() }) const toLogin = () => { authc.value?.loginWithRedirect({ redirect_uri: window.location.origin, authorization_endpoint: 'oauth/authorize', response_mode: 'query', }) } watch(tKey, async () => { tKey.value?.reconstruct() }) const onLogout = async () => { tKey.value?.clean() await authc.value?.logout({ post_logout_redirect_uri: window.location.origin, } as any) } return { authc, tKey, isLogin, toLogin, onLogout, userInfo } } export default useAuthc