()
| 7 | * This ensures backward compatibility while transitioning to the new auth system |
| 8 | */ |
| 9 | export function useAuthStoreIntegration() { |
| 10 | const { user, token, isAuthenticated, isLoading, error } = useAuth(); |
| 11 | const authProvider = useAuthProvider(); |
| 12 | const { setAuthContext, clear: clearStore } = useAuthStore(); |
| 13 | |
| 14 | useEffect(() => { |
| 15 | if (isLoading) { |
| 16 | return; // Don't update store while loading |
| 17 | } |
| 18 | |
| 19 | if (isAuthenticated && user && token) { |
| 20 | // User is authenticated - update store with auth data |
| 21 | const providerForStore = |
| 22 | authProvider.name === 'clerk' |
| 23 | ? 'clerk' |
| 24 | : authProvider.name === 'local' |
| 25 | ? 'local' |
| 26 | : 'custom'; |
| 27 | |
| 28 | // For Clerk: use selected org, or "user's workspace" if no org |
| 29 | let organizationId: string | undefined; |
| 30 | let roles: string[]; |
| 31 | |
| 32 | if (authProvider.name === 'clerk') { |
| 33 | organizationId = user.organizationId || `workspace-${user.id}`; |
| 34 | |
| 35 | // If user is in their own workspace, they are ADMIN by default |
| 36 | if (organizationId === `workspace-${user.id}`) { |
| 37 | roles = ['ADMIN']; |
| 38 | } else { |
| 39 | // If user has an organization role, use it |
| 40 | // Otherwise, grant ADMIN as fallback (matches backend logic when JWT template doesn't include roles) |
| 41 | if (user.organizationRole) { |
| 42 | // Normalize Clerk role format (e.g., "org:admin" -> "ADMIN", "org_member" -> "MEMBER") |
| 43 | let roleUpper = user.organizationRole.toUpperCase(); |
| 44 | // Remove "ORG:" prefix if present |
| 45 | if (roleUpper.startsWith('ORG:')) { |
| 46 | roleUpper = roleUpper.substring(4); |
| 47 | } |
| 48 | // Remove "ORG_" prefix if present |
| 49 | if (roleUpper.startsWith('ORG_')) { |
| 50 | roleUpper = roleUpper.substring(4); |
| 51 | } |
| 52 | roles = [roleUpper]; |
| 53 | } else { |
| 54 | // No org_role in Clerk user object - grant ADMIN as fallback |
| 55 | // This matches the backend behavior when JWT doesn't include org_role |
| 56 | roles = ['ADMIN']; |
| 57 | } |
| 58 | } |
| 59 | } else { |
| 60 | organizationId = user.organizationId || undefined; |
| 61 | roles = user.organizationRole ? [user.organizationRole.toUpperCase()] : ['MEMBER']; |
| 62 | } |
| 63 | |
| 64 | setAuthContext({ |
| 65 | token: token.token, |
| 66 | userId: user.id, |
no test coverage detected