Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(teams): team endpoints no longer require team id (#3201)

Will Hutchinson7253c864fba6
diff --git a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
index 9ec584fc47..127a5be5f7 100644
--- a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
@@ -359,7 +359,7 @@ async function createPendingTeamOnReturn(): Promise<boolean> {
if (invites.length > 0) {
await throwOnErr(() =>
- authServiceClient.inviteToTeam(team.id, { invites })
+ authServiceClient.inviteToTeam({ invites })
);
}
diff --git a/js/app/packages/queries/team/invites.ts b/js/app/packages/queries/team/invites.ts
index 38814177da..fff09bf01e 100644
--- a/js/app/packages/queries/team/invites.ts
+++ b/js/app/packages/queries/team/invites.ts
@@ -15,7 +15,7 @@ export function useTeamInvitesQuery(teamId: Accessor<string>) {
return useQuery(() => ({
queryKey: teamKeys.invites(teamId()).queryKey,
queryFn: async () =>
- await throwOnErr(() => authServiceClient.getTeamInvites(teamId())),
+ await throwOnErr(() => authServiceClient.getTeamInvites()),
enabled: !!teamId(),
}));
}
@@ -31,8 +31,8 @@ type InviteToTeamCallbacks = MutationCallbacks<void, Error, InviteToTeamArgs>;
export function useInviteToTeamMutation(callbacks?: InviteToTeamCallbacks) {
return useMutation(() => ({
- mutationFn: async ({ teamId, request }: InviteToTeamArgs) => {
- await throwOnErr(() => authServiceClient.inviteToTeam(teamId, request));
+ mutationFn: async ({ request }: InviteToTeamArgs) => {
+ await throwOnErr(() => authServiceClient.inviteToTeam(request));
},
...withCallbacks<void, Error, InviteToTeamArgs>(
@@ -67,10 +67,8 @@ export function useDeleteTeamInviteMutation(
callbacks?: DeleteTeamInviteCallbacks
) {
return useMutation(() => ({
- mutationFn: async ({ teamId, teamInviteId }: DeleteTeamInviteArgs) => {
- await throwOnErr(() =>
- authServiceClient.deleteTeamInvite(teamId, teamInviteId)
- );
+ mutationFn: async ({ teamInviteId }: DeleteTeamInviteArgs) => {
+ await throwOnErr(() => authServiceClient.deleteTeamInvite(teamInviteId));
},
...withCallbacks<
diff --git a/js/app/packages/queries/team/members.ts b/js/app/packages/queries/team/members.ts
index b47100927c..6e979ddf42 100644
--- a/js/app/packages/queries/team/members.ts
+++ b/js/app/packages/queries/team/members.ts
@@ -28,10 +28,8 @@ export function usePatchTeamUserTierMutation(
callbacks?: PatchTeamUserTierCallbacks
) {
return useMutation(() => ({
- mutationFn: async ({ teamId, request }: PatchTeamUserTierArgs) => {
- await throwOnErr(() =>
- authServiceClient.patchTeamUserTier(teamId, request)
- );
+ mutationFn: async ({ request }: PatchTeamUserTierArgs) => {
+ await throwOnErr(() => authServiceClient.patchTeamUserTier(request));
},
...withCallbacks<
@@ -113,10 +111,8 @@ export function useRemoveUserFromTeamMutation(
callbacks?: RemoveUserFromTeamCallbacks
) {
return useMutation(() => ({
- mutationFn: async ({ teamId, userId }: RemoveUserFromTeamArgs) => {
- await throwOnErr(() =>
- authServiceClient.removeUserFromTeam(teamId, userId)
- );
+ mutationFn: async ({ userId }: RemoveUserFromTeamArgs) => {
+ await throwOnErr(() => authServiceClient.removeUserFromTeam(userId));
},
...withCallbacks<
diff --git a/js/app/packages/queries/team/teams.ts b/js/app/packages/queries/team/teams.ts
index 348a69c401..a4444d4699 100644
--- a/js/app/packages/queries/team/teams.ts
+++ b/js/app/packages/queries/team/teams.ts
@@ -25,8 +25,7 @@ export function useUserTeamsQuery() {
export function useTeamQuery(teamId: Accessor<string>) {
return useQuery(() => ({
queryKey: teamKeys.detail(teamId()).queryKey,
- queryFn: async () =>
- await throwOnErr(() => authServiceClient.getTeam(teamId())),
+ queryFn: async () => await throwOnErr(() => authServiceClient.getTeam()),
enabled: !!teamId(),
}));
}
@@ -73,8 +72,8 @@ type PatchTeamCallbacks = MutationCallbacks<void, Error, PatchTeamArgs>;
export function usePatchTeamMutation(callbacks?: PatchTeamCallbacks) {
return useMutation(() => ({
- mutationFn: async ({ teamId, request }: PatchTeamArgs) => {
- await throwOnErr(() => authServiceClient.patchTeam(teamId, request));
+ mutationFn: async ({ request }: PatchTeamArgs) => {
+ await throwOnErr(() => authServiceClient.patchTeam(request));
},
...withCallbacks<void, Error, PatchTeamArgs>(
@@ -106,8 +105,8 @@ type DeleteTeamCallbacks = MutationCallbacks<
export function useDeleteTeamMutation(callbacks?: DeleteTeamCallbacks) {
return useMutation(() => ({
- mutationFn: async ({ teamId }: DeleteTeamArgs) => {
- await throwOnErr(() => authServiceClient.deleteTeam(teamId));
+ mutationFn: async (_args: DeleteTeamArgs) => {
+ await throwOnErr(() => authServiceClient.deleteTeam());
},
...withCallbacks<void, Error, DeleteTeamArgs, DeleteTeamContext>(
@@ -172,9 +171,7 @@ export function useCreateTeamWithInvitesMutation(
);
if (invites && invites.length > 0) {
- await throwOnErr(() =>
- authServiceClient.inviteToTeam(team.id, { invites })
- );
+ await throwOnErr(() => authServiceClient.inviteToTeam({ invites }));
}
return team;
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index 8207fc9dd6..80e53f4834 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -603,21 +603,20 @@ export const authServiceClient = {
);
},
- async getTeam(teamId: string) {
+ async getTeam() {
return mapOk(
- await fetchWithAuth<TeamWithMembers>(`${authHost}/team/${teamId}`, {
+ await fetchWithAuth<TeamWithMembers>(`${authHost}/team`, {
method: 'GET',
}),
(result) => result
);
},
- async getTeamInvites(teamId: string) {
+ async getTeamInvites() {
return mapOk(
- await fetchWithAuth<TeamInvitesResponse>(
- `${authHost}/team/${teamId}/invites`,
- { method: 'GET' }
- ),
+ await fetchWithAuth<TeamInvitesResponse>(`${authHost}/team/invites`, {
+ method: 'GET',
+ }),
(result) => result
);
},
@@ -650,9 +649,9 @@ export const authServiceClient = {
);
},
- async patchTeam(teamId: string, args: PatchTeamRequest) {
+ async patchTeam(args: PatchTeamRequest) {
return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/${teamId}`, {
+ await fetchWithAuth<{}>(`${authHost}/team`, {
method: 'PATCH',
body: JSON.stringify(args),
}),
@@ -660,9 +659,9 @@ export const authServiceClient = {
);
},
- async patchTeamUserTier(teamId: string, args: PatchTeamUserTierRequest) {
+ async patchTeamUserTier(args: PatchTeamUserTierRequest) {
return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/${teamId}/tier`, {
+ await fetchWithAuth<{}>(`${authHost}/team/tier`, {
method: 'PATCH',
body: JSON.stringify(args),
}),
@@ -670,9 +669,9 @@ export const authServiceClient = {
);
},
- async inviteToTeam(teamId: string, args: InviteToTeamRequest) {
+ async inviteToTeam(args: InviteToTeamRequest) {
return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/${teamId}/invite`, {
+ await fetchWithAuth<{}>(`${authHost}/team/invite`, {
method: 'POST',
body: JSON.stringify(args),
}),
@@ -680,28 +679,27 @@ export const authServiceClient = {
);
},
- async deleteTeamInvite(teamId: string, teamInviteId: string) {
+ async deleteTeamInvite(teamInviteId: string) {
return mapOk(
- await fetchWithAuth<{}>(
- `${authHost}/team/${teamId}/invite/${teamInviteId}`,
- { method: 'DELETE' }
- ),
+ await fetchWithAuth<{}>(`${authHost}/team/invite/${teamInviteId}`, {
+ method: 'DELETE',
+ }),
() => undefined
);
},
- async removeUserFromTeam(teamId: string, userId: string) {
+ async removeUserFromTeam(userId: string) {
return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/${teamId}/remove/${userId}`, {
+ await fetchWithAuth<{}>(`${authHost}/team/remove/${userId}`, {
method: 'DELETE',
}),
() => undefined
);
},
- async deleteTeam(teamId: string) {
+ async deleteTeam() {
return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/${teamId}`, {
+ await fetchWithAuth<{}>(`${authHost}/team`, {
method: 'DELETE',
}),
() => undefined
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index 5fc14ffa31..64806d847f 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -1683,357 +1683,120 @@ export const sessionLogin = async (
};
/**
- * @summary Creates a new team.
- */
-export type createTeamResponse200 = {
- data: Team;
- status: 200;
-};
-
-export type createTeamResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type createTeamResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type createTeamResponseSuccess = createTeamResponse200 & {
- headers: Headers;
-};
-export type createTeamResponseError = (
- | createTeamResponse400
- | createTeamResponse500
-) & {
- headers: Headers;
-};
-
-export type createTeamResponse =
- | createTeamResponseSuccess
- | createTeamResponseError;
-
-export const getCreateTeamUrl = () => {
- return `/team`;
-};
-
-export const createTeam = async (
- createTeamRequest: CreateTeamRequest,
- options?: RequestInit
-): Promise<createTeamResponse> => {
- const res = await fetch(getCreateTeamUrl(), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(createTeamRequest),
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: createTeamResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as createTeamResponse;
-};
-
-/**
- * @summary Joins a team by accepting an invite.
- */
-export type joinTeamResponse200 = {
- data: void;
- status: 200;
-};
-
-export type joinTeamResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type joinTeamResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type joinTeamResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type joinTeamResponseSuccess = joinTeamResponse200 & {
- headers: Headers;
-};
-export type joinTeamResponseError = (
- | joinTeamResponse400
- | joinTeamResponse401
- | joinTeamResponse500
-) & {
- headers: Headers;
-};
-
-export type joinTeamResponse = joinTeamResponseSuccess | joinTeamResponseError;
-
-export const getJoinTeamUrl = (teamInviteId: string) => {
- return `/team/join/${teamInviteId}`;
-};
-
-export const joinTeam = async (
- teamInviteId: string,
- options?: RequestInit
-): Promise<joinTeamResponse> => {
- const res = await fetch(getJoinTeamUrl(teamInviteId), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: joinTeamResponse['data'] = body ? JSON.parse(body) : {};
- return { data, status: res.status, headers: res.headers } as joinTeamResponse;
-};
-
-/**
- * @summary Rejects an invitation to join a team.
- */
-export type rejectInvitationResponse200 = {
- data: void;
- status: 200;
-};
-
-export type rejectInvitationResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type rejectInvitationResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type rejectInvitationResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type rejectInvitationResponseSuccess = rejectInvitationResponse200 & {
- headers: Headers;
-};
-export type rejectInvitationResponseError = (
- | rejectInvitationResponse400
- | rejectInvitationResponse401
- | rejectInvitationResponse500
-) & {
- headers: Headers;
-};
-
-export type rejectInvitationResponse =
- | rejectInvitationResponseSuccess
- | rejectInvitationResponseError;
-
-export const getRejectInvitationUrl = (teamInviteId: string) => {
- return `/team/join/${teamInviteId}`;
-};
-
-export const rejectInvitation = async (
- teamInviteId: string,
- options?: RequestInit
-): Promise<rejectInvitationResponse> => {
- const res = await fetch(getRejectInvitationUrl(teamInviteId), {
- ...options,
- method: 'DELETE',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: rejectInvitationResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as rejectInvitationResponse;
-};
-
-/**
- * @summary Gets all teams for the authenticated user.
+ * @summary Gets a team by ID.
*/
-export type getUserTeamsResponse200 = {
- data: Team[];
+export type getTeamResponse200 = {
+ data: TeamWithMembers;
status: 200;
};
-export type getUserTeamsResponse400 = {
+export type getTeamResponse400 = {
data: ErrorResponse;
status: 400;
};
-export type getUserTeamsResponse401 = {
+export type getTeamResponse401 = {
data: ErrorResponse;
status: 401;
};
-export type getUserTeamsResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type getUserTeamsResponseSuccess = getUserTeamsResponse200 & {
- headers: Headers;
-};
-export type getUserTeamsResponseError = (
- | getUserTeamsResponse400
- | getUserTeamsResponse401
- | getUserTeamsResponse500
-) & {
- headers: Headers;
-};
-
-export type getUserTeamsResponse =
- | getUserTeamsResponseSuccess
- | getUserTeamsResponseError;
-
-export const getGetUserTeamsUrl = () => {
- return `/team/user`;
-};
-
-export const getUserTeams = async (
- options?: RequestInit
-): Promise<getUserTeamsResponse> => {
- const res = await fetch(getGetUserTeamsUrl(), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: getUserTeamsResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as getUserTeamsResponse;
-};
-
-/**
- * @summary Gets all of a user's invitations.
- */
-export type getUserInvitesResponse200 = {
- data: TeamInvitesResponse;
- status: 200;
-};
-
-export type getUserInvitesResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type getUserInvitesResponse401 = {
+export type getTeamResponse404 = {
data: ErrorResponse;
- status: 401;
+ status: 404;
};
-export type getUserInvitesResponse500 = {
+export type getTeamResponse500 = {
data: ErrorResponse;
status: 500;
};
-export type getUserInvitesResponseSuccess = getUserInvitesResponse200 & {
+export type getTeamResponseSuccess = getTeamResponse200 & {
headers: Headers;
};
-export type getUserInvitesResponseError = (
- | getUserInvitesResponse400
- | getUserInvitesResponse401
- | getUserInvitesResponse500
+export type getTeamResponseError = (
+ | getTeamResponse400
+ | getTeamResponse401
+ | getTeamResponse404
+ | getTeamResponse500
) & {
headers: Headers;
};
-export type getUserInvitesResponse =
- | getUserInvitesResponseSuccess
- | getUserInvitesResponseError;
+export type getTeamResponse = getTeamResponseSuccess | getTeamResponseError;
-export const getGetUserInvitesUrl = () => {
- return `/team/user/invites`;
+export const getGetTeamUrl = () => {
+ return `/team`;
};
-export const getUserInvites = async (
+export const getTeam = async (
options?: RequestInit
-): Promise<getUserInvitesResponse> => {
- const res = await fetch(getGetUserInvitesUrl(), {
+): Promise<getTeamResponse> => {
+ const res = await fetch(getGetTeamUrl(), {
...options,
method: 'GET',
});
const body = [204, 205, 304].includes(res.status) ? null : await res.text();
- const data: getUserInvitesResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as getUserInvitesResponse;
+ const data: getTeamResponse['data'] = body ? JSON.parse(body) : {};
+ return { data, status: res.status, headers: res.headers } as getTeamResponse;
};
/**
- * @summary Gets a team by ID.
+ * @summary Creates a new team.
*/
-export type getTeamResponse200 = {
- data: TeamWithMembers;
+export type createTeamResponse200 = {
+ data: Team;
status: 200;
};
-export type getTeamResponse400 = {
+export type createTeamResponse400 = {
data: ErrorResponse;
status: 400;
};
-export type getTeamResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type getTeamResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
-export type getTeamResponse500 = {
+export type createTeamResponse500 = {
data: ErrorResponse;
status: 500;
};
-export type getTeamResponseSuccess = getTeamResponse200 & {
+export type createTeamResponseSuccess = createTeamResponse200 & {
headers: Headers;
};
-export type getTeamResponseError = (
- | getTeamResponse400
- | getTeamResponse401
- | getTeamResponse404
- | getTeamResponse500
+export type createTeamResponseError = (
+ | createTeamResponse400
+ | createTeamResponse500
) & {
headers: Headers;
};
-export type getTeamResponse = getTeamResponseSuccess | getTeamResponseError;
+export type createTeamResponse =
+ | createTeamResponseSuccess
+ | createTeamResponseError;
-export const getGetTeamUrl = (teamId: string) => {
- return `/team/${teamId}`;
+export const getCreateTeamUrl = () => {
+ return `/team`;
};
-export const getTeam = async (
- teamId: string,
+export const createTeam = async (
+ createTeamRequest: CreateTeamRequest,
options?: RequestInit
-): Promise<getTeamResponse> => {
- const res = await fetch(getGetTeamUrl(teamId), {
+): Promise<createTeamResponse> => {
+ const res = await fetch(getCreateTeamUrl(), {
...options,
- method: 'GET',
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createTeamRequest),
});
const body = [204, 205, 304].includes(res.status) ? null : await res.text();
- const data: getTeamResponse['data'] = body ? JSON.parse(body) : {};
- return { data, status: res.status, headers: res.headers } as getTeamResponse;
+ const data: createTeamResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createTeamResponse;
};
/**
@@ -2076,15 +1839,14 @@ export type deleteTeamResponse =
| deleteTeamResponseSuccess
| deleteTeamResponseError;
-export const getDeleteTeamUrl = (teamId: string) => {
- return `/team/${teamId}`;
+export const getDeleteTeamUrl = () => {
+ return `/team`;
};
export const deleteTeam = async (
- teamId: string,
options?: RequestInit
): Promise<deleteTeamResponse> => {
- const res = await fetch(getDeleteTeamUrl(teamId), {
+ const res = await fetch(getDeleteTeamUrl(), {
...options,
method: 'DELETE',
});
@@ -2143,16 +1905,15 @@ export type patchTeamResponse =
| patchTeamResponseSuccess
| patchTeamResponseError;
-export const getPatchTeamUrl = (teamId: string) => {
- return `/team/${teamId}`;
+export const getPatchTeamUrl = () => {
+ return `/team`;
};
export const patchTeam = async (
- teamId: string,
patchTeamRequest: PatchTeamRequest,
options?: RequestInit
): Promise<patchTeamResponse> => {
- const res = await fetch(getPatchTeamUrl(teamId), {
+ const res = await fetch(getPatchTeamUrl(), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -2219,16 +1980,15 @@ export type inviteToTeamResponse =
| inviteToTeamResponseSuccess
| inviteToTeamResponseError;
-export const getInviteToTeamUrl = (teamId: string) => {
- return `/team/${teamId}/invite`;
+export const getInviteToTeamUrl = () => {
+ return `/team/invite`;
};
export const inviteToTeam = async (
- teamId: string,
inviteToTeamRequest: InviteToTeamRequest,
options?: RequestInit
): Promise<inviteToTeamResponse> => {
- const res = await fetch(getInviteToTeamUrl(teamId), {
+ const res = await fetch(getInviteToTeamUrl(), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -2290,19 +2050,15 @@ export type deleteTeamInviteHandlerResponse =
| deleteTeamInviteHandlerResponseSuccess
| deleteTeamInviteHandlerResponseError;
-export const getDeleteTeamInviteHandlerUrl = (
- teamId: string,
- teamInviteId: string
-) => {
- return `/team/${teamId}/invite/${teamInviteId}`;
+export const getDeleteTeamInviteHandlerUrl = (teamInviteId: string) => {
+ return `/team/invite/${teamInviteId}`;
};
export const deleteTeamInviteHandler = async (
- teamId: string,
teamInviteId: string,
options?: RequestInit
): Promise<deleteTeamInviteHandlerResponse> => {
- const res = await fetch(getDeleteTeamInviteHandlerUrl(teamId, teamInviteId), {
+ const res = await fetch(getDeleteTeamInviteHandlerUrl(teamInviteId), {
...options,
method: 'DELETE',
});
@@ -2357,15 +2113,14 @@ export type getTeamInvitesResponse =
| getTeamInvitesResponseSuccess
| getTeamInvitesResponseError;
-export const getGetTeamInvitesUrl = (teamId: string) => {
- return `/team/${teamId}/invites`;
+export const getGetTeamInvitesUrl = () => {
+ return `/team/invites`;
};
export const getTeamInvites = async (
- teamId: string,
options?: RequestInit
): Promise<getTeamInvitesResponse> => {
- const res = await fetch(getGetTeamInvitesUrl(teamId), {
+ const res = await fetch(getGetTeamInvitesUrl(), {
...options,
method: 'GET',
});
@@ -2380,6 +2135,122 @@ export const getTeamInvites = async (
} as getTeamInvitesResponse;
};
+/**
+ * @summary Joins a team by accepting an invite.
+ */
+export type joinTeamResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type joinTeamResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type joinTeamResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type joinTeamResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type joinTeamResponseSuccess = joinTeamResponse200 & {
+ headers: Headers;
+};
+export type joinTeamResponseError = (
+ | joinTeamResponse400
+ | joinTeamResponse401
+ | joinTeamResponse500
+) & {
+ headers: Headers;
+};
+
+export type joinTeamResponse = joinTeamResponseSuccess | joinTeamResponseError;
+
+export const getJoinTeamUrl = (teamInviteId: string) => {
+ return `/team/join/${teamInviteId}`;
+};
+
+export const joinTeam = async (
+ teamInviteId: string,
+ options?: RequestInit
+): Promise<joinTeamResponse> => {
+ const res = await fetch(getJoinTeamUrl(teamInviteId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: joinTeamResponse['data'] = body ? JSON.parse(body) : {};
+ return { data, status: res.status, headers: res.headers } as joinTeamResponse;
+};
+
+/**
+ * @summary Rejects an invitation to join a team.
+ */
+export type rejectInvitationResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type rejectInvitationResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type rejectInvitationResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type rejectInvitationResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type rejectInvitationResponseSuccess = rejectInvitationResponse200 & {
+ headers: Headers;
+};
+export type rejectInvitationResponseError = (
+ | rejectInvitationResponse400
+ | rejectInvitationResponse401
+ | rejectInvitationResponse500
+) & {
+ headers: Headers;
+};
+
+export type rejectInvitationResponse =
+ | rejectInvitationResponseSuccess
+ | rejectInvitationResponseError;
+
+export const getRejectInvitationUrl = (teamInviteId: string) => {
+ return `/team/join/${teamInviteId}`;
+};
+
+export const rejectInvitation = async (
+ teamInviteId: string,
+ options?: RequestInit
+): Promise<rejectInvitationResponse> => {
+ const res = await fetch(getRejectInvitationUrl(teamInviteId), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: rejectInvitationResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as rejectInvitationResponse;
+};
+
/**
* @summary Removes a user from a team.
*/
@@ -2419,19 +2290,15 @@ export type removeUserFromTeamResponse =
| removeUserFromTeamResponseSuccess
| removeUserFromTeamResponseError;
-export const getRemoveUserFromTeamUrl = (
- teamId: string,
- removeUserId: string
-) => {
- return `/team/${teamId}/remove/${removeUserId}`;
+export const getRemoveUserFromTeamUrl = (removeUserId: string) => {
+ return `/team/remove/${removeUserId}`;
};
export const removeUserFromTeam = async (
- teamId: string,
removeUserId: string,
options?: RequestInit
): Promise<removeUserFromTeamResponse> => {
- const res = await fetch(getRemoveUserFromTeamUrl(teamId, removeUserId), {
+ const res = await fetch(getRemoveUserFromTeamUrl(removeUserId), {
...options,
method: 'DELETE',
});
@@ -2490,16 +2357,15 @@ export type patchTeamUserTierResponse =
| patchTeamUserTierResponseSuccess
| patchTeamUserTierResponseError;
-export const getPatchTeamUserTierUrl = (teamId: string) => {
- return `/team/${teamId}/tier`;
+export const getPatchTeamUserTierUrl = () => {
+ return `/team/tier`;
};
export const patchTeamUserTier = async (
- teamId: string,
patchTeamUserTierRequest: PatchTeamUserTierRequest,
options?: RequestInit
): Promise<patchTeamUserTierResponse> => {
- const res = await fetch(getPatchTeamUserTierUrl(teamId), {
+ const res = await fetch(getPatchTeamUserTierUrl(), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -2516,6 +2382,126 @@ export const patchTeamUserTier = async (
} as patchTeamUserTierResponse;
};
+/**
+ * @summary Gets all teams for the authenticated user.
+ */
+export type getUserTeamsResponse200 = {
+ data: Team[];
+ status: 200;
+};
+
+export type getUserTeamsResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type getUserTeamsResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getUserTeamsResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getUserTeamsResponseSuccess = getUserTeamsResponse200 & {
+ headers: Headers;
+};
+export type getUserTeamsResponseError = (
+ | getUserTeamsResponse400
+ | getUserTeamsResponse401
+ | getUserTeamsResponse500
+) & {
+ headers: Headers;
+};
+
+export type getUserTeamsResponse =
+ | getUserTeamsResponseSuccess
+ | getUserTeamsResponseError;
+
+export const getGetUserTeamsUrl = () => {
+ return `/team/user`;
+};
+
+export const getUserTeams = async (
+ options?: RequestInit
+): Promise<getUserTeamsResponse> => {
+ const res = await fetch(getGetUserTeamsUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getUserTeamsResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getUserTeamsResponse;
+};
+
+/**
+ * @summary Gets all of a user's invitations.
+ */
+export type getUserInvitesResponse200 = {
+ data: TeamInvitesResponse;
+ status: 200;
+};
+
+export type getUserInvitesResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type getUserInvitesResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getUserInvitesResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getUserInvitesResponseSuccess = getUserInvitesResponse200 & {
+ headers: Headers;
+};
+export type getUserInvitesResponseError = (
+ | getUserInvitesResponse400
+ | getUserInvitesResponse401
+ | getUserInvitesResponse500
+) & {
+ headers: Headers;
+};
+
+export type getUserInvitesResponse =
+ | getUserInvitesResponseSuccess
+ | getUserInvitesResponseError;
+
+export const getGetUserInvitesUrl = () => {
+ return `/team/user/invites`;
+};
+
+export const getUserInvites = async (
+ options?: RequestInit
+): Promise<getUserInvitesResponse> => {
+ const res = await fetch(getGetUserInvitesUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getUserInvitesResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getUserInvitesResponse;
+};
+
/**
* @summary Creates a new user.
*/
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 94bede14c2..eed2701a6b 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1398,27 +1398,17 @@
}
},
"/team": {
- "post": {
- "tags": ["teams::inbound::axum_router::create_team"],
- "summary": "Creates a new team.",
- "operationId": "create_team",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/CreateTeamRequest"
- }
- }
- },
- "required": true
- },
+ "get": {
+ "tags": ["teams::inbound::axum_router::get_team"],
+ "summary": "Gets a team by ID.",
+ "operationId": "get_team",
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/Team"
+ "$ref": "#/components/schemas/TeamWithMembers"
}
}
}
@@ -1433,6 +1423,26 @@
}
}
},
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -1444,39 +1454,33 @@
}
}
}
- }
- },
- "/team/join/{team_invite_id}": {
- "get": {
- "tags": ["teams::inbound::axum_router::join_team"],
- "summary": "Joins a team by accepting an invite.",
- "operationId": "join_team",
- "parameters": [
- {
- "name": "team_invite_id",
- "in": "path",
- "description": "The team invite id",
- "required": true,
- "schema": {
- "type": "string"
+ },
+ "post": {
+ "tags": ["teams::inbound::axum_router::create_team"],
+ "summary": "Creates a new team.",
+ "operationId": "create_team",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateTeamRequest"
+ }
}
- }
- ],
+ },
+ "required": true
+ },
"responses": {
"200": {
- "description": ""
- },
- "400": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/Team"
}
}
}
},
- "401": {
+ "400": {
"description": "",
"content": {
"application/json": {
@@ -1499,20 +1503,9 @@
}
},
"delete": {
- "tags": ["teams::inbound::axum_router::reject_invitation"],
- "summary": "Rejects an invitation to join a team.",
- "operationId": "reject_invitation",
- "parameters": [
- {
- "name": "team_invite_id",
- "in": "path",
- "description": "The team invite id",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
+ "tags": ["teams::inbound::axum_router::delete_team"],
+ "summary": "Deletes a team.\nThis will update all team members roles and cancel your subscription for the team.\nThis action is **irreversible** and you will not be able to recover the team afterwards.",
+ "operationId": "delete_team",
"responses": {
"200": {
"description": ""
@@ -1548,28 +1541,36 @@
}
}
}
- }
- },
- "/team/user": {
- "get": {
- "tags": ["teams::inbound::axum_router::get_user_teams"],
- "summary": "Gets all teams for the authenticated user.",
- "operationId": "get_user_teams",
+ },
+ "patch": {
+ "tags": ["teams::inbound::axum_router::patch_team"],
+ "summary": "Updates a team.",
+ "operationId": "patch_team",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchTeamRequest"
+ }
+ }
+ },
+ "required": true
+ },
"responses": {
"200": {
+ "description": ""
+ },
+ "400": {
"description": "",
"content": {
"application/json": {
"schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Team"
- }
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
- "400": {
+ "401": {
"description": "",
"content": {
"application/json": {
@@ -1579,7 +1580,7 @@
}
}
},
- "401": {
+ "404": {
"description": "",
"content": {
"application/json": {
@@ -1602,23 +1603,39 @@
}
}
},
- "/team/user/invites": {
- "get": {
- "tags": ["teams::inbound::axum_router::get_user_invites"],
- "summary": "Gets all of a user's invitations.",
- "operationId": "get_user_invites",
+ "/team/invite": {
+ "post": {
+ "tags": ["teams::inbound::axum_router::invite_to_team"],
+ "summary": "Invites a user to a team.",
+ "operationId": "invite_to_team",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InviteToTeamRequest"
+ }
+ }
+ },
+ "required": true
+ },
"responses": {
- "200": {
+ "201": {
+ "description": ""
+ },
+ "304": {
+ "description": ""
+ },
+ "400": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/TeamInvitesResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
- "400": {
+ "401": {
"description": "",
"content": {
"application/json": {
@@ -1628,7 +1645,7 @@
}
}
},
- "401": {
+ "404": {
"description": "",
"content": {
"application/json": {
@@ -1651,16 +1668,16 @@
}
}
},
- "/team/{team_id}": {
- "get": {
- "tags": ["teams::inbound::axum_router::get_team"],
- "summary": "Gets a team by ID.",
- "operationId": "get_team",
+ "/team/invite/{team_invite_id}": {
+ "delete": {
+ "tags": ["teams::inbound::axum_router::delete_team_invite"],
+ "summary": "Deletes a team invite from a team.",
+ "operationId": "delete_team_invite_handler",
"parameters": [
{
- "name": "team_id",
+ "name": "team_invite_id",
"in": "path",
- "description": "The ID of the team to retrieve",
+ "description": "The ID of the team invite",
"required": true,
"schema": {
"type": "string"
@@ -1669,14 +1686,7 @@
],
"responses": {
"200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/TeamWithMembers"
- }
- }
- }
+ "description": ""
},
"400": {
"description": "",
@@ -1719,25 +1729,23 @@
}
}
}
- },
- "delete": {
- "tags": ["teams::inbound::axum_router::delete_team"],
- "summary": "Deletes a team.\nThis will update all team members roles and cancel your subscription for the team.\nThis action is **irreversible** and you will not be able to recover the team afterwards.",
- "operationId": "delete_team",
- "parameters": [
- {
- "name": "team_id",
- "in": "path",
- "description": "The ID of the team to delete",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
+ }
+ },
+ "/team/invites": {
+ "get": {
+ "tags": ["teams::inbound::axum_router::get_team_invites"],
+ "summary": "Gets all invites for a team.",
+ "operationId": "get_team_invites",
"responses": {
"200": {
- "description": ""
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TeamInvitesResponse"
+ }
+ }
+ }
},
"400": {
"description": "",
@@ -1770,32 +1778,24 @@
}
}
}
- },
- "patch": {
- "tags": ["teams::inbound::axum_router::patch_team"],
- "summary": "Updates a team.",
- "operationId": "patch_team",
+ }
+ },
+ "/team/join/{team_invite_id}": {
+ "get": {
+ "tags": ["teams::inbound::axum_router::join_team"],
+ "summary": "Joins a team by accepting an invite.",
+ "operationId": "join_team",
"parameters": [
{
- "name": "team_id",
+ "name": "team_invite_id",
"in": "path",
- "description": "The ID of the team to update",
+ "description": "The team invite id",
"required": true,
"schema": {
"type": "string"
}
}
],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PatchTeamRequest"
- }
- }
- },
- "required": true
- },
"responses": {
"200": {
"description": ""
@@ -1820,16 +1820,6 @@
}
}
},
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -1841,39 +1831,24 @@
}
}
}
- }
- },
- "/team/{team_id}/invite": {
- "post": {
- "tags": ["teams::inbound::axum_router::invite_to_team"],
- "summary": "Invites a user to a team.",
- "operationId": "invite_to_team",
+ },
+ "delete": {
+ "tags": ["teams::inbound::axum_router::reject_invitation"],
+ "summary": "Rejects an invitation to join a team.",
+ "operationId": "reject_invitation",
"parameters": [
{
- "name": "team_id",
+ "name": "team_invite_id",
"in": "path",
- "description": "The ID of the team to invite to",
+ "description": "The team invite id",
"required": true,
"schema": {
"type": "string"
}
}
],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/InviteToTeamRequest"
- }
- }
- },
- "required": true
- },
"responses": {
- "201": {
- "description": ""
- },
- "304": {
+ "200": {
"description": ""
},
"400": {
@@ -1896,16 +1871,6 @@
}
}
},
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -1919,25 +1884,16 @@
}
}
},
- "/team/{team_id}/invite/{team_invite_id}": {
+ "/team/remove/{remove_user_id}": {
"delete": {
- "tags": ["teams::inbound::axum_router::delete_team_invite"],
- "summary": "Deletes a team invite from a team.",
- "operationId": "delete_team_invite_handler",
+ "tags": ["teams::inbound::axum_router::remove_user_from_team"],
+ "summary": "Removes a user from a team.",
+ "operationId": "remove_user_from_team",
"parameters": [
{
- "name": "team_id",
- "in": "path",
- "description": "The ID of the team",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "team_invite_id",
+ "name": "remove_user_id",
"in": "path",
- "description": "The ID of the team invite",
+ "description": "The ID of the user to remove",
"required": true,
"schema": {
"type": "string"
@@ -1968,16 +1924,6 @@
}
}
},
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -1991,34 +1937,36 @@
}
}
},
- "/team/{team_id}/invites": {
- "get": {
- "tags": ["teams::inbound::axum_router::get_team_invites"],
- "summary": "Gets all invites for a team.",
- "operationId": "get_team_invites",
- "parameters": [
- {
- "name": "team_id",
- "in": "path",
- "description": "The ID of the team to get invites for",
- "required": true,
- "schema": {
- "type": "string"
+ "/team/tier": {
+ "patch": {
+ "tags": ["teams::inbound::axum_router::patch_team_user_tier"],
+ "summary": "Updates a team.",
+ "operationId": "patch_team_user_tier",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchTeamUserTierRequest"
+ }
}
- }
- ],
+ },
+ "required": true
+ },
"responses": {
"200": {
+ "description": ""
+ },
+ "400": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/TeamInvitesResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
- "400": {
+ "401": {
"description": "",
"content": {
"application/json": {
@@ -2028,7 +1976,7 @@
}
}
},
- "401": {
+ "404": {
"description": "",
"content": {
"application/json": {
@@ -2051,34 +1999,24 @@
}
}
},
- "/team/{team_id}/remove/{remove_user_id}": {
- "delete": {
- "tags": ["teams::inbound::axum_router::remove_user_from_team"],
- "summary": "Removes a user from a team.",
- "operationId": "remove_user_from_team",
- "parameters": [
- {
- "name": "team_id",
- "in": "path",
- "description": "The ID of the team",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "remove_user_id",
- "in": "path",
- "description": "The ID of the user to remove",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
+ "/team/user": {
+ "get": {
+ "tags": ["teams::inbound::axum_router::get_user_teams"],
+ "summary": "Gets all teams for the authenticated user.",
+ "operationId": "get_user_teams",
"responses": {
"200": {
- "description": ""
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Team"
+ }
+ }
+ }
+ }
},
"400": {
"description": "",
@@ -2113,47 +2051,23 @@
}
}
},
- "/team/{team_id}/tier": {
- "patch": {
- "tags": ["teams::inbound::axum_router::patch_team_user_tier"],
- "summary": "Updates a team.",
- "operationId": "patch_team_user_tier",
- "parameters": [
- {
- "name": "team_id",
- "in": "path",
- "description": "The ID of the team to update",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PatchTeamUserTierRequest"
- }
- }
- },
- "required": true
- },
+ "/team/user/invites": {
+ "get": {
+ "tags": ["teams::inbound::axum_router::get_user_invites"],
+ "summary": "Gets all of a user's invitations.",
+ "operationId": "get_user_invites",
"responses": {
"200": {
- "description": ""
- },
- "400": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/TeamInvitesResponse"
}
}
}
},
- "401": {
+ "400": {
"description": "",
"content": {
"application/json": {
@@ -2163,7 +2077,7 @@
}
}
},
- "404": {
+ "401": {
"description": "",
"content": {
"application/json": {
diff --git a/js/bun.lock b/js/bun.lock
index abb76fa624..e2ec2551a9 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -839,7 +839,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009", "sha512-XLN+niDA9BkzrxiZqBjYf+DL4TLoMIcI80ypCowacVfrfAjWt0qLwLkzWVUXjD7k3v0DB/G+BP4OLJNkGygHIw=="],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009"],
"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],
@@ -2565,7 +2565,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index fd51c67c91..92c3301812 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -616,6 +616,7 @@ dependencies = [
"document_storage_service_client",
"doppleganger",
"email_validator",
+ "entity_access",
"fusionauth",
"futures",
"github",
@@ -11222,6 +11223,7 @@ dependencies = [
"async-stripe",
"axum",
"chrono",
+ "entity_access",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 71bad8dad3..ae53899d6f 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -42,6 +42,7 @@ cookie = { workspace = true }
document_storage_service_client = { path = "../document_storage_service_client" }
doppleganger = { workspace = true }
email_validator = { path = "../email_validator" }
+entity_access = { path = "../entity_access" }
fusionauth = { path = "../fusionauth" }
futures = { workspace = true }
github = { path = "../github", default-features = false, features = [
@@ -68,7 +69,6 @@ macro_db_client = { path = "../macro_db_client", default-features = false, featu
"team",
] }
macro_entrypoint = { path = "../macro_entrypoint" }
-mobile_welcome_email_db_client = { path = "../mobile_welcome_email_db_client" }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
@@ -76,12 +76,13 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
"tracking",
"user_permissions",
] }
-macro_tower_layers = { path = "../macro_tower_layers" }
macro_service_urls = { path = "../macro_service_urls" }
+macro_tower_layers = { path = "../macro_tower_layers" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
maud = { version = "0.27.0" }
miniserde = "0.1.45"
+mobile_welcome_email_db_client = { path = "../mobile_welcome_email_db_client" }
mockall = { workspace = true }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
@@ -108,8 +109,8 @@ ses_client = { path = "../ses_client" }
sha1 = "0.10.6"
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client", default-features = false, features = [
- "search",
"email",
+ "search",
] }
strum = { workspace = true }
teams = { path = "../teams" }
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 8d63868ed1..cf7492b4fa 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -2,6 +2,8 @@ use std::sync::Arc;
use analytics_client::AnalyticsClient;
use axum::extract::FromRef;
+use entity_access::domain::service::EntityAccessServiceImpl;
+use entity_access::outbound::PgAccessRepository;
use github::domain::service::GithubLinkServiceImpl;
use github::outbound::github_auth_client::GithubAuthImpl;
use github::outbound::github_oauth_client::GithubOauthImpl;
@@ -50,6 +52,8 @@ pub(crate) type ReferralServiceType = ReferralServiceImpl<
pub(crate) type GithubLinkServiceType =
GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;
+pub(crate) type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
@@ -70,6 +74,7 @@ pub(crate) struct ApiContext {
pub user_roles_and_permissions_service:
Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types here
pub teams_service: Arc<TeamsServiceType>,
+ pub entity_access_service: Arc<EntityAccessServiceType>,
pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
pub analytics_client: Arc<AnalyticsClient>,
pub referral_service: Arc<ReferralServiceType>,
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index f0bc59aca4..92d82f83d0 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -98,6 +98,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
teams::inbound::axum_router::teams_router(
teams::inbound::axum_router::TeamRouterState {
service: state.teams_service.clone(),
+ entity_access_service: state.entity_access_service.clone(),
},
)
.layer(
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index d2aa9b445c..0e6fd10bd4 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -5,6 +5,7 @@ use analytics_client::{
use anyhow::Context;
use config::{Config, Environment};
use document_storage_service_client::DocumentStorageServiceClient;
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use github::{
domain::service::{GithubLinkConfig, GithubLinkServiceImpl},
outbound::{
@@ -284,6 +285,9 @@ async fn main() -> anyhow::Result<()> {
notification_ingress: notification_ingress_service.clone(),
};
+ let entity_access_service_impl =
+ EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone()));
+
api::setup_and_serve(
ApiContext {
db,
@@ -310,6 +314,7 @@ async fn main() -> anyhow::Result<()> {
stripe_webhook_secret,
user_roles_and_permissions_service: Arc::new(user_roles_and_permissions_service),
teams_service: Arc::new(teams_service_impl),
+ entity_access_service: Arc::new(entity_access_service_impl),
referral_service: Arc::new(referral_service),
native_app_service: Arc::new(NativeAppServiceImpl {
bundle_fetcher: DefaultBundleFetcher::new(config.environment.app()),
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index b19fd5784c..dee4962769 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -312,6 +312,30 @@ impl<T: RequiredPermission> EntityAccessReceipt<T> {
_marker: PhantomData,
}
}
+
+ /// Dangerously generates an `EntityAccessReceipt` for an authenticated user
+ /// without performing the underlying access check.
+ ///
+ /// **NOTE** This is intended for tests. It **DOES NOT** assert the
+ /// existence of the item or that the user actually has the required
+ /// permission.
+ pub fn dangerously_assert_authenticated_user(
+ user_id: MacroUserIdStr<'static>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> EntityAccessReceipt<T> {
+ EntityAccessReceipt {
+ auth: EntityAccessAuth::Authenticated(user_id),
+ entity: Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ entity_permission: EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ _marker: PhantomData,
+ }
+ }
}
/// Information about a call's channel association and share permission.
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
index 6203a6d35b..b7395a7046 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/mod.rs
@@ -22,7 +22,7 @@ pub use entity_permission::EntityPermissionExtractor;
pub use history::HistoryAccessExtractor;
pub use pin::PinAccessLevelExtractor;
pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractor};
-pub use team::OptionalMacroUserTeamExtractor;
+pub use team::{MacroUserTeamExtractor, OptionalMacroUserTeamExtractor};
pub use thread::ThreadAccessLevelExtractor;
use crate::domain::models::{AccessError, AccessLevel};
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs
index 0c9a8616d4..f061acfc8f 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/team.rs
@@ -20,7 +20,7 @@ use crate::domain::{
};
use model_user::axum_extractor::MacroUserExtractor;
-/// Resolves the authenticated user's team membership and exposes the receipt
+/// Resolves the authenticated user's **OPTIONAL** team membership and exposes the receipt
/// when the user satisfies the required permission `T`.
///
/// `entity_access_receipt` is:
@@ -91,3 +91,65 @@ where
})
}
}
+
+/// Resolves the authenticated user's team membership and exposes the receipt
+/// when the user satisfies the required permission `T`.
+/// Returns `ExtractorError::Unauthorized` if there is no authenticated user or no team.
+#[derive(Debug)]
+pub struct MacroUserTeamExtractor<T: RequiredPermission, Svc> {
+ /// The entity access receipt.
+ pub entity_access_receipt: EntityAccessReceipt<T>,
+ _marker: PhantomData<(T, Svc)>,
+}
+
+impl<T, S, Svc> FromRequestParts<S> for MacroUserTeamExtractor<T, Svc>
+where
+ T: RequiredPermission,
+ Arc<Svc>: FromRef<S>,
+ Svc: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = ExtractorError;
+
+ #[tracing::instrument(err, skip(state, parts))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let service = <Arc<Svc>>::from_ref(state);
+
+ let MacroUserExtractor { macro_user_id, .. } = parts
+ .extract()
+ .await
+ .map_err(|_| ExtractorError::Unauthorized)?;
+
+ let team_info = service
+ .get_user_team(&macro_user_id)
+ .await
+ .map_err(ExtractorError::from)?;
+
+ let Some(team_info) = team_info else {
+ return Err(ExtractorError::UnauthorizedWithMessage("not in a team"));
+ };
+
+ let permission = EntityPermission::TeamRole {
+ role: team_info.role,
+ };
+
+ if !permission.satisfies::<T>() {
+ return Err(ExtractorError::UnauthorizedWithMessage(
+ "you do not have a high enough role",
+ ));
+ }
+
+ Ok(Self {
+ entity_access_receipt: EntityAccessReceipt {
+ entity: Entity {
+ entity_id: team_info.team_id.to_string(),
+ entity_type: EntityType::Team,
+ },
+ auth: EntityAccessAuth::Authenticated(macro_user_id),
+ entity_permission: permission,
+ _marker: PhantomData,
+ },
+ _marker: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.toml
index d21e85dcf1..a6343a28c3 100644
--- a/rust/cloud-storage/teams/Cargo.toml
+++ b/rust/cloud-storage/teams/Cargo.toml
@@ -5,7 +5,15 @@ publish = false
version = "0.1.0"
[features]
-axum = ["dep:axum", "dep:model-error-response", "dep:model_user", "dep:utoipa"]
+axum = [
+ "dep:axum",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+ "entity_access/axum",
+ "entity_access/inbound",
+ "entity_access/ports",
+]
default = ["axum", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
outbound = ["dep:sqlx", "ports"]
@@ -36,6 +44,8 @@ thiserror = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
+entity_access = { path = "../entity_access", default-features = false }
+
# Async runtime (for ports)
tokio = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 1d9fd8f8e7..596abe9932 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -309,6 +309,9 @@ pub enum TeamError {
/// The team invite does not exist
#[error("The team invite does not exist")]
TeamInviteDoesNotExist,
+ /// Underlying entity access error
+ #[error("Access error")]
+ AccessError(#[from] entity_access::domain::models::AccessError),
/// Bad request
#[error("Bad request: {0}")]
BadRequest(String),
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index d591dc454a..6fc785cd71 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -2,6 +2,9 @@
use std::collections::HashSet;
+use entity_access::domain::models::{
+ AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,
+};
use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use crate::domain::model::{
@@ -231,15 +234,14 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Returns the team invites created.
fn invite_users_to_team(
&self,
- team_id: &uuid::Uuid,
- invited_by: &MacroUserIdStr<'_>,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
/// Remove user from a team.
fn remove_user_from_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), RemoveUserFromTeamError>> + Send;
@@ -253,14 +255,14 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Deletes a team invite from a team.
fn delete_team_invite(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
team_invite_id: &uuid::Uuid,
) -> impl Future<Output = Result<(), RemoveTeamInviteError>> + Send;
/// Cancels the team subscription and deletes the team.
fn delete_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
) -> impl Future<Output = Result<(), DeleteTeamError>> + Send;
/// Accepts a team invite for a user
@@ -272,6 +274,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Revokes permissions for all team members (not owner)
/// This is used when a team subscription is canceled or frozen in some way.
+ /// NOTE: this is not exposed via axum and is meant for internal usage within stripe webhook only.
fn revoke_permissions_for_team_members(
&self,
team_id: &uuid::Uuid,
@@ -279,6 +282,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Restores permissions for all team members.
/// This is used when a team subscription becomes active again.
+ /// NOTE: this is not exposed via axum and is meant for internal usage within stripe webhook only.
fn restore_permissions_for_team_members(
&self,
team_id: &uuid::Uuid,
@@ -287,7 +291,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Gets a team by id with all its members
fn get_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,
) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send;
/// Gets all teams for a user
@@ -305,23 +309,16 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Gets all invites for a team
fn get_team_invites(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send;
/// Updates a team
fn patch_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
req: &PatchTeamRequest,
) -> impl Future<Output = Result<(), TeamError>> + Send;
- /// Gets the role of a user in a team
- fn get_team_role(
- &self,
- team_id: &uuid::Uuid,
- user_id: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send;
-
/// Gets the team users permissions
fn get_team_user_permissions(
&self,
@@ -333,7 +330,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Patches the team users tier and updates the stripe subscription accordingly
fn patch_team_user_tier(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
request: &PatchTeamUserTierRequest,
) -> impl Future<Output = Result<(), TeamError>> + Send;
}
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 561554d674..06f5d9e9e5 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -6,6 +6,9 @@ mod test;
use std::{collections::HashSet, sync::Arc};
use anyhow::Context;
+use entity_access::domain::models::{
+ AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,
+};
use macro_user_id::{
cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
};
@@ -316,18 +319,24 @@ where
#[tracing::instrument(skip(self), err)]
async fn invite_users_to_team(
&self,
- team_id: &uuid::Uuid,
- invited_by: &MacroUserIdStr<'_>,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ let invited_by = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|e| InviteUsersToTeamError::TeamError(TeamError::AccessError(e)))?;
+
let invited = self
.team_repository
- .invite_users_to_team(team_id, invited_by, invites)
+ .invite_users_to_team(&team_id, invited_by, invites)
.await?;
// Send notifications for new invites
if !invited.is_empty() {
- let team_name = self.team_repository.get_team_name(team_id).await.ok();
+ let team_name = self.team_repository.get_team_name(&team_id).await.ok();
if let Some(team_name) = team_name {
let invited_by_owned = invited_by.clone().into_owned();
@@ -339,7 +348,7 @@ where
.expect("this cannot fail"),
invite.team_invite_id,
InviteToTeamMetadata {
- team_id: *team_id,
+ team_id,
team_invite_id: invite.team_invite_id,
invited_by: invited_by_owned.clone(),
team_name: team_name.clone(),
@@ -374,20 +383,23 @@ where
#[tracing::instrument(skip(self), err)]
async fn remove_user_from_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
user_id: &MacroUserIdStr<'_>,
) -> Result<(), RemoveUserFromTeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
let removed_member = self
.team_repository
- .remove_user_from_team(team_id, user_id)
+ .remove_user_from_team(&team_id, user_id)
.await?;
self.team_channels_repository
- .remove_team_member_from_channels(team_id, user_id)
+ .remove_team_member_from_channels(&team_id, user_id)
.await?;
let channels_removed = true;
- let subscription_id = match self.get_team_subscription(team_id).await {
+ let subscription_id = match self.get_team_subscription(&team_id).await {
Ok(subscription_id) => subscription_id,
Err(GetTeamSubscriptionError::Customer(e)) => {
self.rollback_remove_user_from_team(&removed_member, channels_removed)
@@ -446,23 +458,32 @@ where
#[tracing::instrument(skip(self), err)]
async fn delete_team_invite(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
team_invite_id: &uuid::Uuid,
) -> Result<(), RemoveTeamInviteError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
self.team_repository
- .delete_team_invite(team_id, team_invite_id)
+ .delete_team_invite(&team_id, team_invite_id)
.await?;
Ok(())
}
#[tracing::instrument(skip(self), err)]
- async fn delete_team(&self, team_id: &uuid::Uuid) -> Result<(), DeleteTeamError> {
- let members = self.team_repository.get_all_team_members(team_id).await?;
+ async fn delete_team(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
+ ) -> Result<(), DeleteTeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ let members = self.team_repository.get_all_team_members(&team_id).await?;
let subscription_id = self
.team_repository
- .get_team_subscription_id(team_id)
+ .get_team_subscription_id(&team_id)
.await?;
if let Some(subscription_id) = subscription_id {
// Cancel subscription
@@ -473,7 +494,7 @@ where
}
self.team_repository
- .delete_team(team_id)
+ .delete_team(&team_id)
.await
.map_err(DeleteTeamError::TeamError)?;
@@ -603,8 +624,13 @@ where
}
#[tracing::instrument(skip(self), err)]
- async fn get_team(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {
- self.team_repository.get_team_by_id(team_id).await
+ async fn get_team(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,
+ ) -> Result<TeamWithMembers, TeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+ self.team_repository.get_team_by_id(&team_id).await
}
#[tracing::instrument(skip(self), err)]
@@ -623,17 +649,22 @@ where
#[tracing::instrument(skip(self), err)]
async fn get_team_invites(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
) -> Result<Vec<TeamInviteDetails>, TeamError> {
- self.team_repository.get_team_invites(team_id).await
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+ self.team_repository.get_team_invites(&team_id).await
}
#[tracing::instrument(skip(self), err)]
async fn patch_team(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
req: &PatchTeamRequest,
) -> Result<(), TeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
if let Some(user_role_updates) = req.user_role_updates.as_ref() {
if user_role_updates.iter().any(|u| u.role == TeamRole::Owner) {
return Err(TeamError::BadRequest(
@@ -642,7 +673,7 @@ where
}
if !user_role_updates.is_empty() {
- let team = self.team_repository.get_team_by_id(team_id).await?;
+ let team = self.team_repository.get_team_by_id(&team_id).await?;
if user_role_updates
.iter()
@@ -655,22 +686,13 @@ where
for update in user_role_updates {
self.team_repository
- .patch_team_user_role(team_id, &update.team_user_id, update.role)
+ .patch_team_user_role(&team_id, &update.team_user_id, update.role)
.await?;
}
}
}
- self.team_repository.patch_team(team_id, req).await
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn get_team_role(
- &self,
- team_id: &uuid::Uuid,
- user_id: &MacroUserIdStr<'_>,
- ) -> Result<Option<TeamRole>, TeamError> {
- self.team_repository.get_team_role(team_id, user_id).await
+ self.team_repository.patch_team(&team_id, req).await
}
#[tracing::instrument(skip(self), err)]
@@ -687,12 +709,14 @@ where
#[tracing::instrument(skip(self), err)]
async fn patch_team_user_tier(
&self,
- team_id: &uuid::Uuid,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
request: &PatchTeamUserTierRequest,
) -> Result<(), TeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
let team_member = self
.team_repository
- .get_team_member(team_id, &request.team_user_id)
+ .get_team_member(&team_id, &request.team_user_id)
.await?;
if team_member.tier == request.new_tier {
@@ -702,12 +726,12 @@ where
}
let team_subscription_id = self
- .get_team_subscription(team_id)
+ .get_team_subscription(&team_id)
.await
.map_err(GetTeamSubscriptionError::into_team_error)?;
self.team_repository
- .patch_team_tier(team_id, &request.team_user_id, request.new_tier)
+ .patch_team_tier(&team_id, &request.team_user_id, request.new_tier)
.await?;
// ensure team member has old tier removed
diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rs
index 8c3e7869bf..3e18c0cd80 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -7,6 +7,9 @@ use std::{
},
};
+use entity_access::domain::models::{
+ AdminTeamRole, EntityAccessReceipt, EntityType, OwnerTeamRole, RequiredPermission,
+};
use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use notification::domain::{
models::{Notification, NotificationResult, request::SendNotificationRequest},
@@ -17,6 +20,17 @@ use roles_and_permissions::domain::{
port::UserRolesAndPermissionsService,
};
+fn test_team_receipt<T: RequiredPermission>(
+ team_id: uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+) -> EntityAccessReceipt<T> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user_id.clone().into_owned(),
+ &team_id.to_string(),
+ EntityType::Team,
+ )
+}
+
use super::*;
use crate::domain::{
customer_repo::CustomerRepository,
@@ -783,8 +797,9 @@ async fn test_invite_marks_sent_only_for_successful_notifications() {
];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
+ let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &invited_by);
let result = service
- .invite_users_to_team(&team_id, &invited_by, invites)
+ .invite_users_to_team(receipt, invites)
.await
.unwrap();
@@ -825,8 +840,9 @@ async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {
)];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
+ let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &invited_by);
service
- .invite_users_to_team(&team_id, &invited_by, invites)
+ .invite_users_to_team(receipt, invites)
.await
.unwrap();
@@ -871,8 +887,9 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {
];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
+ let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &invited_by);
service
- .invite_users_to_team(&team_id, &invited_by, invites)
+ .invite_users_to_team(receipt, invites)
.await
.unwrap();
@@ -928,7 +945,11 @@ async fn test_patch_team_rejects_owner_role_assignment() {
}]),
};
- let err = service.patch_team(&team_id, &req).await.err().unwrap();
+ let receipt = test_team_receipt::<AdminTeamRole>(
+ team_id,
+ &MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ );
+ let err = service.patch_team(receipt, &req).await.err().unwrap();
assert!(matches!(err, TeamError::BadRequest(_)));
assert!(role_calls.lock().unwrap().is_empty());
assert!(name_calls.lock().unwrap().is_empty());
@@ -948,12 +969,13 @@ async fn test_patch_team_rejects_owner_downgrade() {
let req = PatchTeamRequest {
name: None,
user_role_updates: Some(vec![PatchTeamUserRole {
- team_user_id: owner_id,
+ team_user_id: owner_id.clone(),
role: TeamRole::Member,
}]),
};
- let err = service.patch_team(&team_id, &req).await.err().unwrap();
+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);
+ let err = service.patch_team(receipt, &req).await.err().unwrap();
assert!(matches!(err, TeamError::BadRequest(_)));
assert!(role_calls.lock().unwrap().is_empty());
assert!(name_calls.lock().unwrap().is_empty());
@@ -972,7 +994,7 @@ async fn test_patch_team_applies_role_updates_and_name() {
let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
- let team = Team::new(team_id, "Old Name".to_string(), owner_id);
+ let team = Team::new(team_id, "Old Name".to_string(), owner_id.clone());
let (service, role_calls, name_calls) = build_service_with_team(team);
@@ -990,7 +1012,8 @@ async fn test_patch_team_applies_role_updates_and_name() {
]),
};
- service.patch_team(&team_id, &req).await.unwrap();
+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);
+ service.patch_team(receipt, &req).await.unwrap();
let role_calls = role_calls.lock().unwrap();
assert_eq!(role_calls.len(), 2);
@@ -1015,7 +1038,7 @@ async fn test_patch_team_empty_role_updates() {
let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
- let team = Team::new(team_id, "Old Name".to_string(), owner_id);
+ let team = Team::new(team_id, "Old Name".to_string(), owner_id.clone());
let (service, role_calls, name_calls) = build_service_with_team(team);
@@ -1024,7 +1047,8 @@ async fn test_patch_team_empty_role_updates() {
user_role_updates: Some(Vec::new()),
};
- service.patch_team(&team_id, &req).await.unwrap();
+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);
+ service.patch_team(receipt, &req).await.unwrap();
assert!(role_calls.lock().unwrap().is_empty());
let name_calls = name_calls.lock().unwrap();
@@ -1193,8 +1217,9 @@ async fn test_remove_user_from_team_rolls_back_when_decrease_subscription_quanti
},
);
+ let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &user_id);
let err = service
- .remove_user_from_team(&team_id, &user_id)
+ .remove_user_from_team(receipt, &user_id)
.await
.err()
.unwrap();
@@ -1231,8 +1256,9 @@ async fn test_remove_user_from_team_rolls_back_when_get_team_subscription_custom
},
);
+ let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &user_id);
let err = service
- .remove_user_from_team(&team_id, &user_id)
+ .remove_user_from_team(receipt, &user_id)
.await
.err()
.unwrap();
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
index 540394323f..ac5da2d326 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs
@@ -1,4 +1,5 @@
use axum::{Json, extract::State};
+use entity_access::domain::ports::EntityAccessService;
use crate::domain::{model::Team, team_repo::TeamService};
@@ -23,9 +24,9 @@ pub struct CreateTeamRequest {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- State(state): State<TeamRouterState<T>>,
- premium_user: TeamPremiumUserExtractor<T>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ State(state): State<TeamRouterState<T, Eas>>,
+ premium_user: TeamPremiumUserExtractor<T, Eas>,
Json(req): Json<CreateTeamRequest>,
) -> Result<Json<Team>, crate::domain::model::CreateTeamError> {
let team = state
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs
index 3d6300ae3a..bc6f3668d6 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs
@@ -1,20 +1,21 @@
-use axum::extract::{Path, State};
+use axum::extract::State;
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
use model_error_response::ErrorResponse;
use crate::domain::{model::DeleteTeamError, team_repo::TeamService};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Deletes a team.
/// This will update all team members roles and cancel your subscription for the team.
/// This action is **irreversible** and you will not be able to recover the team afterwards.
#[utoipa::path(
delete,
- path = "/team/{team_id}",
+ path = "/team",
operation_id = "delete_team",
- params(
- ("team_id" = String, Path, description = "The ID of the team to delete")
- ),
responses(
(status = 200),
(status = 400, body = ErrorResponse),
@@ -23,11 +24,13 @@ use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor}
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
) -> Result<(), DeleteTeamError> {
- state.service.delete_team(&team_id).await?;
+ state
+ .service
+ .delete_team(access.entity_access_receipt)
+ .await?;
Ok(())
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs
index 02056349a5..2aac9e938a 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs
@@ -1,15 +1,17 @@
use axum::extract::{Path, State};
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
use model_error_response::ErrorResponse;
use crate::domain::{model::RemoveTeamInviteError, team_repo::TeamService};
-use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Path parameters for delete team invite endpoint.
#[derive(serde::Deserialize)]
pub struct Param {
- /// The team ID.
- pub team_id: uuid::Uuid,
/// The team invite ID.
pub team_invite_id: uuid::Uuid,
}
@@ -17,10 +19,9 @@ pub struct Param {
/// Deletes a team invite from a team.
#[utoipa::path(
delete,
- path = "/team/{team_id}/invite/{team_invite_id}",
+ path = "/team/invite/{team_invite_id}",
operation_id = "delete_team_invite_handler",
params(
- ("team_id" = String, Path, description = "The ID of the team"),
("team_invite_id" = String, Path, description = "The ID of the team invite")
),
responses(
@@ -32,17 +33,14 @@ pub struct Param {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(Param {
- team_id,
- team_invite_id,
- }): Path<Param>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
+ Path(Param { team_invite_id }): Path<Param>,
) -> Result<(), RemoveTeamInviteError> {
state
.service
- .delete_team_invite(&team_id, &team_invite_id)
+ .delete_team_invite(access.entity_access_receipt, &team_invite_id)
.await?;
Ok(())
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs
index 26d8d6d1d7..bde8603e17 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs
@@ -1,6 +1,7 @@
-use axum::{
- Json,
- extract::{Path, State},
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::MemberTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -9,16 +10,13 @@ use crate::domain::{
team_repo::TeamService,
};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Gets a team by ID.
#[utoipa::path(
get,
- path = "/team/{team_id}",
+ path = "/team",
operation_id = "get_team",
- params(
- ("team_id" = String, Path, description = "The ID of the team to retrieve")
- ),
responses(
(status = 200, body = TeamWithMembers),
(status = 400, body = ErrorResponse),
@@ -28,11 +26,10 @@ use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor}
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::MemberRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
) -> Result<Json<TeamWithMembers>, TeamError> {
- let team = state.service.get_team(&team_id).await?;
+ let team = state.service.get_team(access.entity_access_receipt).await?;
Ok(Json(team))
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs
index cc17767838..31a650c056 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs
@@ -1,6 +1,7 @@
-use axum::{
- Json,
- extract::{Path, State},
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::AdminTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -9,7 +10,7 @@ use crate::domain::{
team_repo::TeamService,
};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Response containing a list of team invites
#[derive(serde::Serialize, utoipa::ToSchema)]
@@ -21,11 +22,8 @@ pub struct TeamInvitesResponse {
/// Gets all invites for a team.
#[utoipa::path(
get,
- path = "/team/{team_id}/invites",
+ path = "/team/invites",
operation_id = "get_team_invites",
- params(
- ("team_id" = String, Path, description = "The ID of the team to get invites for")
- ),
responses(
(status = 200, body = TeamInvitesResponse),
(status = 400, body = ErrorResponse),
@@ -34,11 +32,13 @@ pub struct TeamInvitesResponse {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
) -> Result<Json<TeamInvitesResponse>, TeamError> {
- let invites = state.service.get_team_invites(&team_id).await?;
+ let invites = state
+ .service
+ .get_team_invites(access.entity_access_receipt)
+ .await?;
Ok(Json(TeamInvitesResponse { invites }))
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs
index 87eaac1662..723baa00ea 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs
@@ -1,4 +1,5 @@
use axum::{Json, extract::State};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
@@ -29,8 +30,8 @@ pub struct TeamInvitesResponse {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- State(state): State<TeamRouterState<T>>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ State(state): State<TeamRouterState<T, Eas>>,
user_context: MacroUserExtractor,
) -> Result<Json<TeamInvitesResponse>, TeamError> {
let invites = state
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs
index 734737dfe9..96726018db 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs
@@ -1,4 +1,5 @@
use axum::{Json, extract::State};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
@@ -22,8 +23,8 @@ use super::TeamRouterState;
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- State(state): State<TeamRouterState<T>>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ State(state): State<TeamRouterState<T, Eas>>,
user_context: MacroUserExtractor,
) -> Result<Json<Vec<Team>>, TeamError> {
let teams = state
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
index 4974c08356..0515539f81 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
@@ -1,18 +1,17 @@
-use axum::{
- Json,
- extract::{Path, State},
- http::StatusCode,
+use axum::{Json, extract::State, http::StatusCode};
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
};
use macro_user_id::{email::Email, lowercased::Lowercase};
use model_error_response::ErrorResponse;
-use model_user::axum_extractor::MacroUserExtractor;
use crate::domain::{
model::{InviteUsersToTeamError, TeamUserTier},
team_repo::TeamService,
};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// A single invite entry with email and tier
#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema, Clone)]
@@ -82,11 +81,8 @@ impl axum::response::IntoResponse for InviteToTeamError {
/// Invites a user to a team.
#[utoipa::path(
post,
- path = "/team/{team_id}/invite",
+ path = "/team/invite",
operation_id = "invite_to_team",
- params(
- ("team_id" = String, Path, description = "The ID of the team to invite to")
- ),
request_body = InviteToTeamRequest,
responses(
(status = 201),
@@ -98,11 +94,9 @@ impl axum::response::IntoResponse for InviteToTeamError {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
- State(state): State<TeamRouterState<T>>,
- user_context: MacroUserExtractor,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
Json(req): Json<InviteToTeamRequest>,
) -> Result<StatusCode, InviteToTeamError> {
let parsed: Vec<Result<(Email<Lowercase<'_>>, TeamUserTier), _>> = req
@@ -124,7 +118,7 @@ pub async fn handler<T: TeamService>(
let team_invites = state
.service
- .invite_users_to_team(&team_id, &user_context.macro_user_id, invites)
+ .invite_users_to_team(access.entity_access_receipt, invites)
.await
.map_err(InviteToTeamError::InviteUsersToTeamError)?;
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs
index 5f53724d32..67a1a40971 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs
@@ -1,4 +1,5 @@
use axum::extract::{Path, State};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
@@ -29,8 +30,8 @@ pub struct TeamInvitePathParam {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- State(state): State<TeamRouterState<T>>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ State(state): State<TeamRouterState<T, Eas>>,
user_context: MacroUserExtractor,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<(), JoinTeamError> {
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs b/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs
index bd253dd7f6..83c65979d1 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs
@@ -4,143 +4,25 @@ use std::marker::PhantomData;
use axum::{
Json, RequestPartsExt,
- extract::{FromRef, FromRequestParts, Path},
+ extract::{FromRef, FromRequestParts},
http::{StatusCode, request::Parts},
response::{IntoResponse, Response},
};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
-use crate::domain::{model::TeamRole, team_repo::TeamService};
+use crate::domain::team_repo::TeamService;
-use super::{TeamPathParam, TeamRouterState};
-
-/// Marker for member-level access
-#[derive(Debug)]
-pub struct MemberRole;
-
-/// Marker for admin-level access
-#[derive(Debug)]
-pub struct AdminRole;
-
-/// Marker for owner-level access
-#[derive(Debug)]
-pub struct OwnerRole;
-
-trait BuildTeamAccess {
- fn into_team_role() -> TeamRole;
-}
-
-impl BuildTeamAccess for MemberRole {
- fn into_team_role() -> TeamRole {
- TeamRole::Member
- }
-}
-
-impl BuildTeamAccess for AdminRole {
- fn into_team_role() -> TeamRole {
- TeamRole::Admin
- }
-}
-
-impl BuildTeamAccess for OwnerRole {
- fn into_team_role() -> TeamRole {
- TeamRole::Owner
- }
-}
-
-/// Extractor that verifies the user has at least the required role in the team.
-#[derive(Debug)]
-pub struct TeamAccessRoleExtractor<Role, TS: TeamService> {
- #[expect(dead_code)]
- role: TeamRole,
- _role: PhantomData<Role>,
- _ts: PhantomData<TS>,
-}
-
-/// Errors from team access role extraction
-#[derive(Debug, thiserror::Error)]
-pub enum RoleAccessErr {
- /// Team id not found in path params
- #[error("Team id not found in path params")]
- MissingTeamId,
- /// User context failed to extract
- #[error("Internal server err")]
- UserContextErr,
- /// Failed to get team role
- #[error("Failed to get team role")]
- DbErr(#[from] crate::domain::model::TeamError),
- /// User is not a member of this team
- #[error("User is not a member of this team")]
- NotInTeam,
- /// User does not have access to the desired resource
- #[error("User does not have access to the desired resource")]
- NotHighEnoughAccess,
-}
-
-impl IntoResponse for RoleAccessErr {
- fn into_response(self) -> Response {
- let err = Json(ErrorResponse {
- message: self.to_string().into(),
- });
- match self {
- RoleAccessErr::MissingTeamId => (StatusCode::BAD_REQUEST, err),
- RoleAccessErr::UserContextErr => (StatusCode::INTERNAL_SERVER_ERROR, err),
- RoleAccessErr::DbErr(_) => (StatusCode::INTERNAL_SERVER_ERROR, err),
- RoleAccessErr::NotInTeam => (StatusCode::UNAUTHORIZED, err),
- RoleAccessErr::NotHighEnoughAccess => (StatusCode::UNAUTHORIZED, err),
- }
- .into_response()
- }
-}
-
-impl<S, Role, TS> FromRequestParts<S> for TeamAccessRoleExtractor<Role, TS>
-where
- TeamRouterState<TS>: FromRef<S>,
- S: Send + Sync + Clone + 'static,
- Role: BuildTeamAccess,
- TS: TeamService,
-{
- type Rejection = RoleAccessErr;
-
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let router_state = TeamRouterState::<TS>::from_ref(state);
-
- let user_context: MacroUserExtractor = parts
- .extract()
- .await
- .map_err(|_| RoleAccessErr::UserContextErr)?;
-
- let Path(TeamPathParam { team_id }) = parts
- .extract()
- .await
- .map_err(|_| RoleAccessErr::MissingTeamId)?;
-
- let team_role = router_state
- .service
- .get_team_role(&team_id, &user_context.macro_user_id)
- .await?;
-
- let team_role = team_role.ok_or(RoleAccessErr::NotInTeam)?;
-
- if team_role < Role::into_team_role() {
- return Err(RoleAccessErr::NotHighEnoughAccess);
- }
-
- Ok(Self {
- role: team_role,
- _role: PhantomData,
- _ts: PhantomData,
- })
- }
-}
+use super::TeamRouterState;
/// Extractor that verifies the user has a specific permission, exposing the
/// user context so the handler doesn't need to extract it again.
-pub struct TeamPremiumUserExtractor<TS: TeamService> {
+pub struct TeamPremiumUserExtractor<TS: TeamService, Eas: EntityAccessService> {
/// The authenticated user context, available for use by the handler.
pub user_context: MacroUserExtractor,
_ts: PhantomData<TS>,
+ _eas: PhantomData<Eas>,
}
/// Errors from premium user extraction
@@ -180,16 +62,17 @@ const CREATE_TEAM_PERMISSION: [PermissionId; 2] = [
PermissionId::WriteStripeSubscription,
];
-impl<S, TS> FromRequestParts<S> for TeamPremiumUserExtractor<TS>
+impl<S, TS, Eas> FromRequestParts<S> for TeamPremiumUserExtractor<TS, Eas>
where
- TeamRouterState<TS>: FromRef<S>,
+ TeamRouterState<TS, Eas>: FromRef<S>,
S: Send + Sync + Clone + 'static,
TS: TeamService,
+ Eas: EntityAccessService,
{
type Rejection = PremiumUserErr;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let router_state = TeamRouterState::<TS>::from_ref(state);
+ let router_state = TeamRouterState::<TS, Eas>::from_ref(state);
let user_context: MacroUserExtractor = parts
.extract()
@@ -210,6 +93,7 @@ where
Ok(Self {
user_context,
_ts: PhantomData,
+ _eas: PhantomData,
})
}
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
index 525a787f36..9af8a374ae 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -36,10 +36,12 @@ use std::sync::Arc;
use axum::{
Json, Router,
+ extract::FromRef,
http::StatusCode,
response::{IntoResponse, Response},
routing::{delete, get, patch, post},
};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use crate::domain::{
@@ -50,56 +52,59 @@ use crate::domain::{
team_repo::TeamService,
};
-/// Shared path param for team endpoints.
-#[derive(serde::Deserialize)]
-pub struct TeamPathParam {
- /// The team id
- pub team_id: uuid::Uuid,
-}
-
/// Router state containing the team service.
-pub struct TeamRouterState<T> {
+pub struct TeamRouterState<T, Eas> {
/// The team service implementation.
pub service: Arc<T>,
+ /// The entity access service.
+ pub entity_access_service: Arc<Eas>,
+}
+
+impl<T, Eas> FromRef<TeamRouterState<T, Eas>> for Arc<Eas> {
+ fn from_ref(state: &TeamRouterState<T, Eas>) -> Self {
+ state.entity_access_service.clone()
+ }
}
-// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).
-impl<T> Clone for TeamRouterState<T> {
+// Manual Clone impl so T, Eas doesn't need to be Clone (it's behind Arc).
+impl<T, Eas> Clone for TeamRouterState<T, Eas> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
}
}
}
/// Build the teams router with all endpoints.
-pub fn teams_router<T, S>(state: TeamRouterState<T>) -> Router<S>
+pub fn teams_router<T, Eas, S>(state: TeamRouterState<T, Eas>) -> Router<S>
where
T: TeamService,
+ Eas: EntityAccessService,
S: Send + Sync + 'static,
{
Router::new()
- .route("/", post(create_team::handler::<T>))
- .route("/join/{team_invite_id}", get(join_team::handler::<T>))
- .route("/user", get(get_user_teams::handler::<T>))
- .route("/user/invites", get(get_user_invites::handler::<T>))
- .route("/{team_id}", get(get_team::handler::<T>))
- .route("/{team_id}", patch(patch_team::handler::<T>))
- .route("/{team_id}/tier", patch(patch_team_user_tier::handler::<T>))
- .route("/{team_id}", delete(delete_team::handler::<T>))
- .route("/{team_id}/invites", get(get_team_invites::handler::<T>))
- .route("/{team_id}/invite", post(invite_to_team::handler::<T>))
+ .route("/", post(create_team::handler::<T, Eas>))
+ .route("/join/{team_invite_id}", get(join_team::handler::<T, Eas>))
+ .route("/user", get(get_user_teams::handler::<T, Eas>))
+ .route("/user/invites", get(get_user_invites::handler::<T, Eas>))
+ .route("/", get(get_team::handler::<T, Eas>))
+ .route("/", patch(patch_team::handler::<T, Eas>))
+ .route("/tier", patch(patch_team_user_tier::handler::<T, Eas>))
+ .route("/", delete(delete_team::handler::<T, Eas>))
+ .route("/invites", get(get_team_invites::handler::<T, Eas>))
+ .route("/invite", post(invite_to_team::handler::<T, Eas>))
.route(
"/join/{team_invite_id}",
- delete(reject_invitation::handler::<T>),
+ delete(reject_invitation::handler::<T, Eas>),
)
.route(
- "/{team_id}/remove/{remove_user_id}",
- delete(remove_user_from_team::handler::<T>),
+ "/remove/{remove_user_id}",
+ delete(remove_user_from_team::handler::<T, Eas>),
)
.route(
- "/{team_id}/invite/{team_invite_id}",
- delete(delete_team_invite::handler::<T>),
+ "/invite/{team_invite_id}",
+ delete(delete_team_invite::handler::<T, Eas>),
)
.with_state(state)
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs
index f1c5abc363..cbfbcae851 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs
@@ -1,6 +1,7 @@
-use axum::{
- Json,
- extract::{Path, State},
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::AdminTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -9,16 +10,13 @@ use crate::domain::{
team_repo::TeamService,
};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Updates a team.
#[utoipa::path(
patch,
- path = "/team/{team_id}",
+ path = "/team",
operation_id = "patch_team",
- params(
- ("team_id" = String, Path, description = "The ID of the team to update")
- ),
request_body = PatchTeamRequest,
responses(
(status = 200),
@@ -29,12 +27,14 @@ use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor}
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
Json(req): Json<PatchTeamRequest>,
) -> Result<(), TeamError> {
- state.service.patch_team(&team_id, &req).await?;
+ state
+ .service
+ .patch_team(access.entity_access_receipt, &req)
+ .await?;
Ok(())
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
index 0b255bbcd1..ed354bf5a1 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
@@ -1,6 +1,7 @@
-use axum::{
- Json,
- extract::{Path, State},
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -9,16 +10,13 @@ use crate::domain::{
team_repo::TeamService,
};
-use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Updates a team.
#[utoipa::path(
patch,
- path = "/team/{team_id}/tier",
+ path = "/team/tier",
operation_id = "patch_team_user_tier",
- params(
- ("team_id" = String, Path, description = "The ID of the team to update")
- ),
request_body = PatchTeamUserTierRequest,
responses(
(status = 200),
@@ -29,12 +27,14 @@ use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor}
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
Json(req): Json<PatchTeamUserTierRequest>,
) -> Result<(), TeamError> {
- state.service.patch_team_user_tier(&team_id, &req).await?;
+ state
+ .service
+ .patch_team_user_tier(access.entity_access_receipt, &req)
+ .await?;
Ok(())
}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs b/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs
index 2fafd097da..75cf13dee7 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs
@@ -1,4 +1,5 @@
use axum::extract::{Path, State};
+use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
@@ -29,8 +30,8 @@ pub struct TeamInvitePathParam {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- State(state): State<TeamRouterState<T>>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ State(state): State<TeamRouterState<T, Eas>>,
user_context: MacroUserExtractor,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<(), RemoveTeamInviteError> {
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs
index d8af3b633c..80a04ef4b8 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs
@@ -1,16 +1,18 @@
use axum::extract::{Path, State};
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use crate::domain::{model::RemoveUserFromTeamError, team_repo::TeamService};
-use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};
+use super::TeamRouterState;
/// Path parameters for remove user endpoint.
#[derive(serde::Deserialize)]
pub struct Param {
- /// The team ID.
- pub team_id: uuid::Uuid,
/// The ID of the user to remove.
pub remove_user_id: MacroUserIdStr<'static>,
}
@@ -18,10 +20,9 @@ pub struct Param {
/// Removes a user from a team.
#[utoipa::path(
delete,
- path = "/team/{team_id}/remove/{remove_user_id}",
+ path = "/team/remove/{remove_user_id}",
operation_id = "remove_user_from_team",
params(
- ("team_id" = String, Path, description = "The ID of the team"),
("remove_user_id" = String, Path, description = "The ID of the user to remove")
),
responses(
@@ -32,17 +33,14 @@ pub struct Param {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService>(
- _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
- State(state): State<TeamRouterState<T>>,
- Path(Param {
- team_id,
- remove_user_id,
- }): Path<Param>,
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
+ Path(Param { remove_user_id }): Path<Param>,
) -> Result<(), RemoveUserFromTeamError> {
state
.service
- .remove_user_from_team(&team_id, &remove_user_id)
+ .remove_user_from_team(access.entity_access_receipt, &remove_user_id)
.await?;
Ok(())
}