-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseSession.ts
More file actions
128 lines (113 loc) · 3.42 KB
/
useSession.ts
File metadata and controls
128 lines (113 loc) · 3.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Session hook for Studio.
*
* Wraps `client.auth.me()` (=> `GET /api/v1/auth/get-session`) to expose
* "who is signed in" + a logout entry point. Studio defers actual login
* to `apps/account`; if the session call returns no user, the layout
* bounces the browser to the Account login page.
*
* Organization / project / multi-tenant state lived on this hook in
* previous versions and was removed when Studio collapsed onto a single
* unscoped backend. The session response's `activeOrganizationId` is
* still surfaced so plugins that care can read it, but Studio does no
* org switching itself.
*/
import {
createContext,
createElement,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import { useClient } from '@objectstack/client-react';
export interface SessionUser {
id: string;
email?: string;
name?: string;
image?: string | null;
emailVerified?: boolean;
}
export interface SessionData {
id: string;
userId: string;
token?: string;
expiresAt?: string;
activeOrganizationId?: string | null;
}
export interface SessionState {
user: SessionUser | null;
session: SessionData | null;
loading: boolean;
error: Error | null;
refresh: () => Promise<void>;
logout: () => Promise<void>;
}
const SessionContext = createContext<SessionState | null>(null);
function normaliseSessionResponse(raw: any): {
user: SessionUser | null;
session: SessionData | null;
} {
if (!raw) return { user: null, session: null };
const payload = raw.data !== undefined ? raw.data : raw;
if (!payload) return { user: null, session: null };
return { user: payload.user ?? null, session: payload.session ?? null };
}
export function SessionProvider({ children }: { children: ReactNode }) {
const client = useClient() as any;
const [user, setUser] = useState<SessionUser | null>(null);
const [session, setSession] = useState<SessionData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const refresh = useCallback(async () => {
if (!client?.auth) return;
setLoading(true);
setError(null);
try {
const raw = await client.auth.me();
const { user: u, session: s } = normaliseSessionResponse(raw);
setUser(u);
setSession(s);
} catch (err) {
setError(err as Error);
setUser(null);
setSession(null);
} finally {
setLoading(false);
}
}, [client]);
useEffect(() => {
refresh();
}, [refresh]);
const logout = useCallback(async () => {
if (!client?.auth) return;
try {
await client.auth.logout();
} finally {
setUser(null);
setSession(null);
}
}, [client]);
const value = useMemo<SessionState>(
() => ({ user, session, loading, error, refresh, logout }),
[user, session, loading, error, refresh, logout],
);
return createElement(SessionContext.Provider, { value }, children);
}
export function useSession(): SessionState {
const ctx = useContext(SessionContext);
if (!ctx) {
throw new Error('useSession must be used inside <SessionProvider>.');
}
return ctx;
}
/**
* @deprecated Studio no longer scopes by organization. Returns `undefined`.
*/
export function useActiveOrganizationId(): string | undefined {
const { session } = useSession();
return session?.activeOrganizationId ?? undefined;
}