-
Notifications
You must be signed in to change notification settings - Fork 232
feat(permissions): add useAccessibleOrgs hook and export getPermissionKeys #1793
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
Merged
pontusringblom
merged 3 commits into
layer5io:master
from
rishiraj38:feat/accessible-orgs-hook
Aug 12, 2026
+178
−0
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| import { useLazyGetUserKeysQuery } from '@meshery/schemas/cloudApi'; | ||
| import { Key } from '@meshery/schemas/permissions'; | ||
| import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; | ||
| import { getPermissionKeys, isPermissionKeySet, PermissionKeySpec } from './PermissionProvider'; | ||
|
|
||
| /** | ||
| * For a given set of user keys (as returned by `getUserKeys`), check whether | ||
| * the `permissionKey` spec is satisfied. | ||
| * | ||
| * Uses case-insensitive comparison on the `function` field, matching the | ||
| * `canKey` pattern in host applications. | ||
| */ | ||
| const orgHasPermission = ( | ||
| orgKeys: Array<{ id: string; function: string }>, | ||
| spec: PermissionKeySpec | ||
| ): boolean => { | ||
| const userHasKey = (key: Key) => | ||
| orgKeys.some( | ||
| (k) => k.id === key.id && k.function?.toLowerCase() === key.function?.toLowerCase() | ||
| ); | ||
|
|
||
| if (!isPermissionKeySet(spec)) { | ||
| return userHasKey(spec); | ||
| } | ||
|
|
||
| const keys = getPermissionKeys(spec); | ||
| if (keys.length === 0) return false; | ||
|
|
||
| const specObj = spec as { anyOf?: Key[] }; | ||
| if ('anyOf' in specObj) { | ||
| return keys.some(userHasKey); | ||
| } | ||
| return keys.every(userHasKey); | ||
| }; | ||
|
|
||
| /** Type guard: narrows any object with an optional `id` to one with a definite `id`. */ | ||
| const hasDefiniteId = <T extends { id?: string }>(org: T): org is T & { id: string } => | ||
| Boolean(org.id); | ||
|
|
||
| /** | ||
| * Configuration for `useAccessibleOrgs`. | ||
| * | ||
| * The hook does NOT read orgs or the current org from any global store — both | ||
| * are supplied by the host application so the hook stays framework-agnostic. | ||
| * | ||
| * Generic over `T` so the element type of `allOrgs` flows through to | ||
| * `accessibleOrgs` — callers keep `org.name`, `org.avatar`, etc. typed. | ||
| */ | ||
| export interface UseAccessibleOrgsOptions<T extends { id?: string } = { id?: string }> { | ||
| /** All organizations the user belongs to (e.g. from `useGetOrgsQuery`). */ | ||
| allOrgs?: T[]; | ||
|
|
||
| /** The id of the organization the user is currently in. Excluded from results. */ | ||
| currentOrgId?: string; | ||
|
|
||
| /** Whether the org list has finished loading. */ | ||
| orgsLoaded: boolean; | ||
|
|
||
| /** The permission key (or key set) to check each org against. */ | ||
| permissionKey?: PermissionKeySpec; | ||
| } | ||
|
|
||
| /** | ||
| * Returns only those organizations where the user holds the permission(s) | ||
| * described by `permissionKey`. The current org is excluded from the result | ||
| * since the user is already on the 403 page for it. | ||
| * | ||
| * Queries `/api/identity/orgs/:orgId/users/keys` for each org in parallel | ||
| * via `useLazyGetUserKeysQuery`. This is a 403-page-only hook — the N | ||
| * parallel requests are acceptable because this page is not a hot path. | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // In meshery-cloud | ||
| * const { data: allOrgs, isSuccess } = useGetActiveOrgs(); | ||
| * const currentOrg = useSelector(selectCurrentOrg); | ||
| * const { accessibleOrgs, isLoading } = useAccessibleOrgs({ | ||
| * allOrgs, | ||
| * currentOrgId: currentOrg?.id, | ||
| * orgsLoaded: isSuccess, | ||
| * permissionKey, | ||
| * }); | ||
| * ``` | ||
| */ | ||
| export const useAccessibleOrgs = <T extends { id?: string }>({ | ||
| allOrgs, | ||
| currentOrgId, | ||
| orgsLoaded, | ||
| permissionKey | ||
| }: UseAccessibleOrgsOptions<T>) => { | ||
| const [triggerGetKeys] = useLazyGetUserKeysQuery(); | ||
|
|
||
| // Track which orgs have been checked and their results. | ||
| // Map<orgId, hasPermission> | ||
| const [checkedOrgs, setCheckedOrgs] = useState<Map<string, boolean>>(new Map()); | ||
| const [isChecking, setIsChecking] = useState(false); | ||
|
|
||
| // Stable ref to avoid re-triggering the effect on every state update | ||
| const checkedRef = useRef<Set<string>>(new Set()); | ||
|
|
||
| // Reset caches when the permission requirement changes so stale results | ||
| // from a previous key are never served. | ||
| useEffect(() => { | ||
| checkedRef.current.clear(); | ||
| setCheckedOrgs(new Map()); | ||
| }, [permissionKey]); | ||
|
|
||
| const checkOrgs = useCallback(async () => { | ||
| if (!allOrgs || !orgsLoaded || !permissionKey) return; | ||
|
|
||
| // Only check orgs we haven't already checked | ||
| const orgsToCheck = allOrgs | ||
| .filter(hasDefiniteId) | ||
| .filter((org) => org.id !== currentOrgId && !checkedRef.current.has(org.id)); | ||
|
|
||
| if (orgsToCheck.length === 0) return; | ||
|
|
||
| setIsChecking(true); | ||
|
|
||
| // Mark these as being checked to prevent duplicate requests | ||
| orgsToCheck.forEach((org) => checkedRef.current.add(org.id)); | ||
|
|
||
| // Fire all queries in parallel | ||
| const results = await Promise.allSettled( | ||
| orgsToCheck.map(async (org) => { | ||
| const result = await triggerGetKeys({ orgId: org.id }).unwrap(); | ||
| const keys = result?.keys ?? []; | ||
| return { orgId: org.id, hasPermission: orgHasPermission(keys, permissionKey) }; | ||
| }) | ||
| ); | ||
|
|
||
| setCheckedOrgs((prev) => { | ||
| const next = new Map(prev); | ||
| for (const [index, r] of results.entries()) { | ||
| const orgId = orgsToCheck[index].id; | ||
| if (r.status === 'fulfilled') { | ||
| next.set(orgId, r.value.hasPermission); | ||
| } else { | ||
| // On failure, record as inaccessible so isReady can still resolve | ||
| next.set(orgId, false); | ||
| } | ||
| } | ||
| return next; | ||
| }); | ||
|
|
||
| setIsChecking(false); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }, [allOrgs, orgsLoaded, permissionKey, currentOrgId, triggerGetKeys]); | ||
|
|
||
| useEffect(() => { | ||
| checkOrgs(); | ||
| }, [checkOrgs]); | ||
|
|
||
| const accessibleOrgs = useMemo(() => { | ||
| if (!allOrgs) return []; | ||
| return allOrgs | ||
| .filter(hasDefiniteId) | ||
| .filter((org) => org.id !== currentOrgId && checkedOrgs.get(org.id) === true); | ||
| }, [allOrgs, currentOrgId, checkedOrgs]); | ||
|
|
||
| const otherOrgs = (allOrgs ?? []) | ||
| .filter(hasDefiniteId) | ||
| .filter((org) => org.id !== currentOrgId); | ||
|
|
||
| const isReady = orgsLoaded && !isChecking && otherOrgs.every((org) => checkedOrgs.has(org.id)); | ||
|
|
||
| return { | ||
| accessibleOrgs, | ||
| isReady, | ||
| isLoading: !orgsLoaded || isChecking, | ||
| hasNoAccessibleOrgs: isReady && accessibleOrgs.length === 0 | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Invalidate permission results when the permission requirement changes.
checkedRefandcheckedOrgsare keyed only by organization ID. WhenpermissionKeychanges, Line 107 suppresses new requests for already checked organizations. The hook can then return access results for the previous permission requirement.Associate each request batch with its permission requirement. Clear the result cache when that requirement changes. Ignore results from an older batch after a newer requirement becomes active. Keep
isCheckingscoped to the active batch.Also applies to: 101-137
🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch in theory, but in practice permissionKey is set once from the 403 page's permission shield and never changes during the component lifecycle. The useCallback dep array already includes permissionKey so if it did change, the effect re-fires. That said, I'll add a reset of checkedRef when permissionKey changes for correctness doesn't hurt.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@rishiraj38, agreed. The 403-page lifecycle makes this low risk in the current caller.If
permissionKeycan change, reset bothcheckedRefandcheckedOrgs. Also guard in-flight responses so an older request cannot populate the cache after the new requirement becomes active. Resetting onlycheckedRefcan still expose results from the previous requirement.🐇
✏️ Learnings added
🧠 Learnings used
You are interacting with an AI system.