Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/data/organizations/members-query.ts
2501 views
1
/**
2
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { OrganizationMember, OrganizationRole } from "@gitpod/public-api/lib/gitpod/v1/organization_pb";
8
import { useQuery, useQueryClient } from "@tanstack/react-query";
9
import { useCallback, useMemo } from "react";
10
import { organizationClient } from "../../service/public-api";
11
import { useCurrentUser } from "../../user-context";
12
import { useCurrentOrg } from "./orgs-query";
13
14
export function useOrganizationMembersInvalidator() {
15
const organizationId = useCurrentOrg().data?.id;
16
const queryClient = useQueryClient();
17
return useCallback(() => {
18
queryClient.invalidateQueries(getQueryKey(organizationId));
19
}, [organizationId, queryClient]);
20
}
21
22
export function useListOrganizationMembers() {
23
const organizationId = useCurrentOrg().data?.id;
24
const query = useQuery<OrganizationMember[], Error>(
25
getQueryKey(organizationId),
26
async () => {
27
const response = await organizationClient.listOrganizationMembers({
28
organizationId,
29
pagination: {
30
pageSize: 1000,
31
},
32
});
33
return response.members;
34
},
35
{
36
enabled: !!organizationId,
37
},
38
);
39
return query;
40
}
41
42
export function useIsOwner(): boolean {
43
const role = useMemberRole();
44
return role === OrganizationRole.OWNER;
45
}
46
47
export function useMemberRole(): OrganizationRole {
48
const user = useCurrentUser();
49
const members = useListOrganizationMembers();
50
return useMemo(
51
() => members.data?.find((m) => m.userId === user?.id)?.role ?? OrganizationRole.UNSPECIFIED,
52
[members.data, user?.id],
53
);
54
}
55
56
const roleScore: Record<OrganizationRole, number> = {
57
[OrganizationRole.UNSPECIFIED]: 0,
58
[OrganizationRole.COLLABORATOR]: 1,
59
[OrganizationRole.MEMBER]: 2,
60
[OrganizationRole.OWNER]: 3,
61
};
62
63
// Would be better to align schema.yaml but we can do it simple for now
64
export function useHasRolePermission(role: OrganizationRole): boolean {
65
const userRole = useMemberRole();
66
return useMemo(() => {
67
if (userRole === OrganizationRole.UNSPECIFIED) {
68
return false;
69
}
70
return roleScore[userRole] >= roleScore[role];
71
}, [role, userRole]);
72
}
73
74
function getQueryKey(organizationId: string | undefined) {
75
return ["listOrganizationMembers", organizationId || "undefined"];
76
}
77
78