Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sessionClaims to useAuth #4823

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions .changeset/honest-oranges-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@clerk/astro': patch
'@clerk/clerk-react': patch
'@clerk/types': patch
'@clerk/vue': patch
---

Expose `sessionClaims` from `useAuth` hooks
80 changes: 10 additions & 70 deletions packages/astro/src/react/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import type {
ActJWTClaim,
CheckAuthorizationWithCustomPermissions,
Clerk,
GetToken,
OrganizationCustomRoleKey,
SignOut,
} from '@clerk/types';
import type { Clerk, GetToken, SignOut, UseAuthReturn } from '@clerk/types';
import type { Store, StoreValue } from 'nanostores';
import { useCallback, useSyncExternalStore } from 'react';

Expand All @@ -15,9 +8,6 @@ import { authAsyncStorage } from '#async-local-storage';
import { $authStore } from '../stores/external';
import { $clerk, $csrState } from '../stores/internal';

type CheckAuthorizationSignedOut = undefined;
type CheckAuthorizationWithoutOrgOrUser = (params?: Parameters<CheckAuthorizationWithCustomPermissions>[0]) => false;

/**
* @internal
*/
Expand Down Expand Up @@ -54,60 +44,6 @@ const createSignOut = () => {
};
};

type UseAuthReturn =
| {
isLoaded: false;
isSignedIn: undefined;
userId: undefined;
sessionId: undefined;
actor: undefined;
orgId: undefined;
orgRole: undefined;
orgSlug: undefined;
has: CheckAuthorizationSignedOut;
signOut: SignOut;
getToken: GetToken;
}
| {
isLoaded: true;
isSignedIn: false;
userId: null;
sessionId: null;
actor: null;
orgId: null;
orgRole: null;
orgSlug: null;
has: CheckAuthorizationWithoutOrgOrUser;
signOut: SignOut;
getToken: GetToken;
}
| {
isLoaded: true;
isSignedIn: true;
userId: string;
sessionId: string;
actor: ActJWTClaim | null;
orgId: null;
orgRole: null;
orgSlug: null;
has: CheckAuthorizationWithoutOrgOrUser;
signOut: SignOut;
getToken: GetToken;
}
| {
isLoaded: true;
isSignedIn: true;
userId: string;
sessionId: string;
actor: ActJWTClaim | null;
orgId: string;
orgRole: OrganizationCustomRoleKey;
orgSlug: string | null;
has: CheckAuthorizationWithCustomPermissions;
signOut: SignOut;
getToken: GetToken;
};

type UseAuth = () => UseAuthReturn;

/**
Expand Down Expand Up @@ -142,13 +78,13 @@ type UseAuth = () => UseAuthReturn;
* }
*/
export const useAuth: UseAuth = () => {
const { sessionId, userId, actor, orgId, orgRole, orgSlug, orgPermissions } = useStore($authStore);
const { sessionId, sessionClaims, userId, actor, orgId, orgRole, orgSlug, orgPermissions } = useStore($authStore);

const getToken: GetToken = useCallback(createGetToken(), []);
const signOut: SignOut = useCallback(createSignOut(), []);

const has = useCallback(
(params: Parameters<CheckAuthorizationWithCustomPermissions>[0]) => {
const has = useCallback<NonNullable<UseAuthReturn['has']>>(
params => {
if (!params?.permission && !params?.role) {
throw new Error(
'Missing parameters. `has` from `useAuth` requires a permission or role key to be passed. Example usage: `has({permission: "org:posts:edit"`',
Expand Down Expand Up @@ -177,6 +113,7 @@ export const useAuth: UseAuth = () => {
isLoaded: false,
isSignedIn: undefined,
sessionId,
sessionClaims: undefined,
userId,
actor: undefined,
orgId: undefined,
Expand All @@ -193,6 +130,7 @@ export const useAuth: UseAuth = () => {
isLoaded: true,
isSignedIn: false,
sessionId,
sessionClaims: null,
userId,
actor: null,
orgId: null,
Expand All @@ -204,11 +142,12 @@ export const useAuth: UseAuth = () => {
};
}

if (!!sessionId && !!userId && !!orgId && !!orgRole) {
if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {
return {
isLoaded: true,
isSignedIn: true,
sessionId,
sessionClaims,
userId,
actor: actor || null,
orgId,
Expand All @@ -220,11 +159,12 @@ export const useAuth: UseAuth = () => {
};
}

if (!!sessionId && !!userId && !orgId) {
if (!!sessionId && !!sessionClaims && !!userId && !orgId) {
return {
isLoaded: true,
isSignedIn: true,
sessionId,
sessionClaims,
userId,
actor: actor || null,
orgId: null,
Expand Down
3 changes: 2 additions & 1 deletion packages/react/src/contexts/AuthContext.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { createContextAndHook } from '@clerk/shared/react';
import type { ActJWTClaim, OrganizationCustomPermissionKey, OrganizationCustomRoleKey } from '@clerk/types';
import type { ActJWTClaim, JwtPayload, OrganizationCustomPermissionKey, OrganizationCustomRoleKey } from '@clerk/types';

export type AuthContextValue = {
userId: string | null | undefined;
sessionId: string | null | undefined;
sessionClaims: JwtPayload | null | undefined;
actor: ActJWTClaim | null | undefined;
orgId: string | null | undefined;
orgRole: OrganizationCustomRoleKey | null | undefined;
Expand Down
60 changes: 41 additions & 19 deletions packages/react/src/hooks/__tests__/useAuth.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createCheckAuthorization } from '@clerk/shared/authorization';
import { ClerkInstanceContext } from '@clerk/shared/react';
import type { LoadedClerk } from '@clerk/types';
import type { LoadedClerk, UseAuthReturn } from '@clerk/types';
import { render, renderHook } from '@testing-library/react';
import React from 'react';
import { afterAll, beforeAll, beforeEach, describe, expect, expectTypeOf, it, test, vi } from 'vitest';
Expand All @@ -24,6 +24,21 @@ vi.mock('../../errors/errorThrower', () => ({
},
}));

const stubSessionClaims = (input: {
sessionId: string;
userId: string;
orgId?: string;
}): NonNullable<UseAuthReturn['sessionClaims']> => ({
__raw: '',
exp: 1,
iat: 1,
iss: '',
nbf: 1,
sid: input.sessionId,
sub: input.userId,
org_id: input.orgId,
});

const TestComponent = () => {
const { isLoaded, isSignedIn } = useAuth();
return (
Expand Down Expand Up @@ -77,6 +92,7 @@ describe('useDerivedAuth', () => {
expect(current.isLoaded).toBe(false);
expect(current.isSignedIn).toBeUndefined();
expect(current.sessionId).toBeUndefined();
expect(current.sessionClaims).toBeUndefined();
expect(current.userId).toBeUndefined();
expect(current.actor).toBeUndefined();
expect(current.orgId).toBeUndefined();
Expand All @@ -92,6 +108,7 @@ describe('useDerivedAuth', () => {
expect(current.isLoaded).toBe(true);
expect(current.isSignedIn).toBe(false);
expect(current.sessionId).toBeNull();
expect(current.sessionClaims).toBeNull();
expect(current.userId).toBeNull();
expect(current.actor).toBeNull();
expect(current.orgId).toBeNull();
Expand All @@ -104,27 +121,29 @@ describe('useDerivedAuth', () => {
it('returns signed in with org context when sessionId, userId, orgId, and orgRole are present', () => {
const authObject = {
sessionId: 'session123',
sessionClaims: stubSessionClaims({ sessionId: 'session123', userId: 'user123' }),
userId: 'user123',
actor: 'actor123',
actor: { sub: 'actor123' },
orgId: 'org123',
orgRole: 'admin',
orgSlug: 'my-org',
signOut: vi.fn(),
getToken: vi.fn(),
};
} satisfies Partial<UseAuthReturn>;

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.actor).toBe('actor123');
expect(current.orgId).toBe('org123');
expect(current.orgRole).toBe('admin');
expect(current.orgSlug).toBe('my-org');
expect(current.sessionId).toBe(authObject.sessionId);
expect(current.userId).toBe(authObject.userId);
expect(current.sessionClaims).toBe(authObject.sessionClaims);
expect(current.actor?.sub).toBe(authObject.actor.sub);
expect(current.orgId).toBe(authObject.orgId);
expect(current.orgRole).toBe(authObject.orgRole);
expect(current.orgSlug).toBe(authObject.orgSlug);
expect(typeof current.has).toBe('function');
expect(current.signOut).toBe(authObject.signOut);
expect(current.getToken).toBe(authObject.getToken);
Expand All @@ -136,21 +155,23 @@ describe('useDerivedAuth', () => {

it('returns signed in without org context when sessionId and userId are present but no orgId', () => {
const authObject = {
sessionId: 'session123',
userId: 'user123',
actor: 'actor123',
sessionId: 'session123',
sessionClaims: stubSessionClaims({ sessionId: 'session123', userId: 'user123' }),
actor: { sub: 'actor123' },
signOut: vi.fn(),
getToken: vi.fn(),
};
} satisfies Partial<UseAuthReturn>;
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.actor).toBe('actor123');
expect(current.sessionId).toBe(authObject.sessionId);
expect(current.userId).toBe(authObject.userId);
expect(current.sessionClaims).toBe(authObject.sessionClaims);
expect(current.actor?.sub).toBe(authObject.actor.sub);
expect(current.orgId).toBeNull();
expect(current.orgRole).toBeNull();
expect(current.orgSlug).toBeNull();
Expand All @@ -165,9 +186,9 @@ describe('useDerivedAuth', () => {

it('throws invalid state error if none of the conditions match', () => {
const authObject = {
sessionId: true,
userId: undefined,
};
sessionId: 'session123',
} satisfies Partial<UseAuthReturn>;
renderHook(() => useDerivedAuth(authObject));

// eslint-disable-next-line @typescript-eslint/unbound-method
Expand All @@ -177,10 +198,11 @@ describe('useDerivedAuth', () => {
it('uses provided has function if available', () => {
const mockHas = vi.fn().mockReturnValue(false);
const authObject = {
sessionId: 'session123',
userId: 'user123',
sessionId: 'session123',
sessionClaims: stubSessionClaims({ sessionId: 'session123', userId: 'user123' }),
has: mockHas,
};
} satisfies Partial<UseAuthReturn>;
const {
result: { current },
} = renderHook(() => useDerivedAuth(authObject));
Expand Down
13 changes: 10 additions & 3 deletions packages/react/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,16 @@ export const useAuth: UseAuth = (initialAuthState = {}) => {
authContext = initialAuthState != null ? initialAuthState : {};
}

const { sessionId, userId, actor, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } = authContext;
const { sessionId, sessionClaims, userId, actor, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =
authContext;
const isomorphicClerk = useIsomorphicClerkContext();

const getToken: GetToken = useCallback(createGetToken(isomorphicClerk), [isomorphicClerk]);
const signOut: SignOut = useCallback(createSignOut(isomorphicClerk), [isomorphicClerk]);

return useDerivedAuth({
sessionId,
sessionClaims,
userId,
actor,
orgId,
Expand Down Expand Up @@ -106,6 +108,7 @@ export const useAuth: UseAuth = (initialAuthState = {}) => {
export function useDerivedAuth(authObject: any): UseAuthReturn {
const {
sessionId,
sessionClaims,
userId,
actor,
orgId,
Expand Down Expand Up @@ -139,6 +142,7 @@ export function useDerivedAuth(authObject: any): UseAuthReturn {
isLoaded: false,
isSignedIn: undefined,
sessionId,
sessionClaims: undefined,
userId,
actor: undefined,
orgId: undefined,
Expand All @@ -155,6 +159,7 @@ export function useDerivedAuth(authObject: any): UseAuthReturn {
isLoaded: true,
isSignedIn: false,
sessionId,
sessionClaims: null,
userId,
actor: null,
orgId: null,
Expand All @@ -166,11 +171,12 @@ export function useDerivedAuth(authObject: any): UseAuthReturn {
};
}

if (!!sessionId && !!userId && !!orgId && !!orgRole) {
if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {
return {
isLoaded: true,
isSignedIn: true,
sessionId,
sessionClaims,
userId,
actor: actor || null,
orgId,
Expand All @@ -182,11 +188,12 @@ export function useDerivedAuth(authObject: any): UseAuthReturn {
};
}

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