-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseSession.ts
More file actions
290 lines (264 loc) · 7.85 KB
/
useSession.ts
File metadata and controls
290 lines (264 loc) · 7.85 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Session + Organization hooks for Studio.
*
* These hooks sit on top of the better-auth session endpoint
* (`GET /api/v1/auth/get-session`) and the organization plugin endpoints
* (`/api/v1/auth/organization/**`), both wrapped by
* `packages/client/src/index.ts`.
*
* The three-layer model:
*
* HTTP cookie → `session.activeOrganizationId` → `X-Environment-Id` header
* (who) (which org) (which DB)
*
* Studio uses `SessionProvider` (below) as the single React source of truth
* for "who is logged in and which org is active." Consumers call
* `useSession()` / `useActiveOrganizationId()` / `useOrganizations()`.
*/
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>;
setActiveOrganization: (organizationId: string) => Promise<void>;
organizations: Organization[];
organizationsLoading: boolean;
reloadOrganizations: () => Promise<void>;
}
export interface Organization {
id: string;
name: string;
slug?: string;
logo?: string;
metadata?: Record<string, unknown> | null;
}
const SessionContext = createContext<SessionState | null>(null);
/**
* Normalise the better-auth `/get-session` response shape. Depending on the
* version, the body is either `{ user, session }` directly or wrapped in
* `{ data: { user, session } }`. Also handles the older `{ data: null }`
* "not logged in" shape.
*/
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 };
const user = payload.user ?? null;
const session = payload.session ?? null;
return { user, session };
}
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 [organizations, setOrganizations] = useState<Organization[]>([]);
const [organizationsLoading, setOrganizationsLoading] = useState(false);
const reloadOrganizations = useCallback(async () => {
if (!client?.organizations) return;
setOrganizationsLoading(true);
try {
const result = await client.organizations.list();
setOrganizations(result?.organizations ?? []);
} catch {
setOrganizations([]);
} finally {
setOrganizationsLoading(false);
}
}, [client]);
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]);
useEffect(() => {
if (user) {
reloadOrganizations();
} else {
setOrganizations([]);
}
}, [user, reloadOrganizations]);
const logout = useCallback(async () => {
if (!client?.auth) return;
try {
await client.auth.logout();
} finally {
setUser(null);
setSession(null);
setOrganizations([]);
}
}, [client]);
const setActiveOrganization = useCallback(
async (organizationId: string) => {
if (!client?.organizations) return;
await client.organizations.setActive(organizationId);
await refresh();
},
[client, refresh],
);
const value = useMemo<SessionState>(
() => ({
user,
session,
loading,
error,
refresh,
logout,
setActiveOrganization,
organizations,
organizationsLoading,
reloadOrganizations,
}),
[
user,
session,
loading,
error,
refresh,
logout,
setActiveOrganization,
organizations,
organizationsLoading,
reloadOrganizations,
],
);
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;
}
/**
* Convenience selector for the currently-active organization id (taken from
* the session). Returns `undefined` if no org is selected.
*/
export function useActiveOrganizationId(): string | undefined {
const { session } = useSession();
return session?.activeOrganizationId ?? undefined;
}
/**
* Hook: list every organization the current user belongs to.
*
* Backed by the shared state in {@link SessionProvider}, so every caller
* (top-bar switcher, org list page, new-org redirect) sees the same list
* and a single reload refreshes them all.
*/
export function useOrganizations() {
const { organizations, organizationsLoading, reloadOrganizations } = useSession();
return {
organizations,
loading: organizationsLoading,
error: null as Error | null,
reload: reloadOrganizations,
};
}
/**
* Hook: provision a new organization via better-auth.
*/
export function useCreateOrganization() {
const client = useClient() as any;
const [creating, setCreating] = useState(false);
const [error, setError] = useState<Error | null>(null);
const create = useCallback(
async (req: { name: string; slug?: string }) => {
if (!client?.organizations) throw new Error('Client not ready');
setCreating(true);
setError(null);
try {
return await client.organizations.create(req);
} catch (err) {
setError(err as Error);
throw err;
} finally {
setCreating(false);
}
},
[client],
);
return { create, creating, error };
}
/**
* Hook: cascade-delete an organization.
*
* Wraps `client.organizations.delete(id)` (which hits
* `DELETE /api/v1/cloud/organizations/:id`). The server tears down every
* project owned by the organization (including each project's physical
* database) before dropping the org row itself.
*
* On success the local session + organization list are refreshed so the
* deleted org disappears from the switcher and `activeOrganizationId`
* gets cleared if it pointed at this org.
*/
export function useDeleteOrganization() {
const client = useClient() as any;
const { reloadOrganizations, refresh } = useSession();
const [deleting, setDeleting] = useState(false);
const [error, setError] = useState<Error | null>(null);
const remove = useCallback(
async (organizationId: string) => {
if (!client?.organizations?.delete) throw new Error('Client not ready');
setDeleting(true);
setError(null);
try {
const result = await client.organizations.delete(organizationId);
await reloadOrganizations();
await refresh();
return result;
} catch (err) {
setError(err as Error);
throw err;
} finally {
setDeleting(false);
}
},
[client, reloadOrganizations, refresh],
);
return { remove, deleting, error };
}