Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions packages/react/src/hooks/__tests__/useAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,49 @@ describe('useDerivedAuth', () => {
expect(errorThrower.throw).toHaveBeenCalledWith(invalidStateError);
});

it('returns loading state when sessionId and userId are present but sessionClaims is missing', () => {
const authObject = {
sessionId: 'session123',
userId: 'user123',
signOut: vi.fn(),
getToken: vi.fn(),
};

const {
result: { current },
} = renderHook(() => useDerivedAuth(authObject));

expect(current.isLoaded).toBe(false);
expect(current.isSignedIn).toBeUndefined();
expect(current.sessionId).toBeUndefined();
expect(current.userId).toBeUndefined();
expect(current.sessionClaims).toBeUndefined();
});

it('returns signed in without org when orgId is present but orgRole is missing', () => {
const authObject = {
sessionId: 'session123',
sessionClaims: stubSessionClaims({ sessionId: 'session123', userId: 'user123', orgId: 'org123' }),
userId: 'user123',
orgId: 'org123',
orgRole: undefined,
signOut: vi.fn(),
getToken: vi.fn(),
};

const {
result: { current },
} = renderHook(() => useDerivedAuth(authObject));

expect(current.isLoaded).toBe(true);
expect(current.isSignedIn).toBe(true);
expect(current.sessionId).toBe('session123');
expect(current.userId).toBe('user123');
expect(current.orgId).toBeNull();
expect(current.orgRole).toBeNull();
expect(current.orgSlug).toBeNull();
});

it('uses provided has function if available', () => {
const mockHas = vi.fn().mockReturnValue(false);
const authObject = {
Expand Down
21 changes: 20 additions & 1 deletion packages/shared/src/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,25 @@ const resolveAuthState = ({
} as const;
}

// Session exists but claims aren't available yet (e.g. during client hydration
// before a token has been fetched). Treat as loading state.
if (!!sessionId && !!userId && !sessionClaims) {
return {
actor: undefined,
getToken,
has: () => false,
isLoaded: false,
isSignedIn: undefined,
orgId: undefined,
orgRole: undefined,
orgSlug: undefined,
sessionClaims: undefined,
sessionId: undefined,
signOut,
userId: undefined,
} as const;
}

if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {
return {
actor: actor || null,
Expand All @@ -359,7 +378,7 @@ const resolveAuthState = ({
} as const;
}

if (!!sessionId && !!sessionClaims && !!userId && !orgId) {
if (!!sessionId && !!sessionClaims && !!userId) {
return {
actor: actor || null,
getToken,
Expand Down
Loading