Files
console-dev/app/lib/useOAuth.js
T

46 lines
1.4 KiB
JavaScript

/** OAuth 授权发起器:校验提供商和返回 URL,再整页跳转;不在前端构造第三方授权参数。 */
import { onBeforeUnmount } from "vue";
import { ref } from "vue";
import { useApi } from "~/lib/auth.js";
import { r as oauth_r } from "~/lib/oauth.js";
function i() {
let i = useApi(),
a = ref(!1),
o = ref(``),
s = !0;
onBeforeUnmount(() => {
s = !1;
});
// busy 防止重复发起,卸载标记防止用户离开页面后被迟到的授权响应再次跳走。
async function c(e) {
if (s && !a.value) {
if (((o.value = ``), !/^[a-z][a-z0-9_]*$/i.test(e))) {
o.value = `授权方式无效`;
return;
}
a.value = !0;
try {
let t = await i.get(`/oauth/${encodeURIComponent(e)}`);
if (!s) return;
let n = oauth_r(t?.url, window.location.origin);
if (!n) throw Error(`授权地址无效,请联系支持`);
try {
// 仅记录当前标签页曾发起授权,不存储 OAuth 凭证或 JWT。
sessionStorage.setItem(`console-oauth-pending`, `1`);
} catch {}
window.location.assign(n);
} catch (e) {
s && (o.value = e instanceof Error ? e.message : `授权失败`);
} finally {
s && (a.value = !1);
}
}
}
return {
busy: a,
error: o,
start: c,
};
}
export { i as t };