forked from EduCraft/curriculum-project-hub
46ce942aec
Unscoped GET /auth/feishu is disabled by default. Derive org slug from /admin/org/:slug, ?org=, or the Alpha Silo hostname and redirect to /auth/feishu/:orgSlug so the login button works on tenant domains.
71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import { writable } from 'svelte/store';
|
|
import { api, type MeResponse } from './api';
|
|
|
|
interface SessionState {
|
|
loading: boolean;
|
|
me: MeResponse | null;
|
|
error: string | null;
|
|
}
|
|
|
|
export const session = writable<SessionState>({
|
|
loading: true,
|
|
me: null,
|
|
error: null,
|
|
});
|
|
|
|
export async function loadSession(): Promise<void> {
|
|
session.update((s) => ({ ...s, loading: true, error: null }));
|
|
try {
|
|
const me = await api.me();
|
|
session.set({ loading: false, me, error: null });
|
|
} catch (err) {
|
|
const status = (err as { status?: number }).status;
|
|
if (status === 401) {
|
|
redirectToLogin();
|
|
return;
|
|
}
|
|
session.set({
|
|
loading: false,
|
|
me: null,
|
|
error: err instanceof Error ? err.message : String(err),
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolve org slug for org-scoped Feishu OAuth (`GET /auth/feishu/:orgSlug`).
|
|
* Unscoped `/auth/feishu` is disabled unless allowLegacyFeishuOAuth is on.
|
|
*/
|
|
export function resolveLoginOrgSlug(): string | null {
|
|
const path = window.location.pathname.split('/').filter(Boolean);
|
|
if (path[0] === 'admin' && path[1] === 'org' && path[2]) {
|
|
return decodeURIComponent(path[2]);
|
|
}
|
|
const q = new URLSearchParams(window.location.search).get('org');
|
|
if (q && q.trim() !== '') return q.trim();
|
|
|
|
// Alpha Silo public host: <slug>.educraft.paradigm-edu.net (or educraft-dev)
|
|
const host = window.location.hostname.toLowerCase();
|
|
const m = host.match(/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.educraft(?:-dev)?\./);
|
|
if (m?.[1]) return m[1];
|
|
return null;
|
|
}
|
|
|
|
export function redirectToLogin(): void {
|
|
const ret = encodeURIComponent(
|
|
window.location.pathname + window.location.search + window.location.hash,
|
|
);
|
|
const slug = resolveLoginOrgSlug();
|
|
if (slug === null) {
|
|
// Need an org slug for scoped OAuth — backend login helper can prompt.
|
|
window.location.href = `/admin/login?returnTo=${ret}`;
|
|
return;
|
|
}
|
|
window.location.href = `/auth/feishu/${encodeURIComponent(slug)}?returnTo=${ret}`;
|
|
}
|
|
|
|
export async function logout(): Promise<void> {
|
|
await api.logout();
|
|
redirectToLogin();
|
|
}
|