Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Show teammate profile pictures on the team roster (#8158)

ConnorYoh26233095b2a0
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
index fc21f24cd5..f6f309f2c7 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
@@ -621,6 +621,8 @@ public class ProprietaryUIDataController {
summary.setPortalAccess(portalAccessUserIds.contains(user.getId()));
summary.setUsername(user.getUsername());
summary.setEmail(user.getEmail());
+ summary.setSupabaseId(
+ user.getSupabaseId() == null ? null : user.getSupabaseId().toString());
summary.setRoleName(user.getRoleName());
summary.setRolesAsString(user.getRolesAsString());
summary.setEnabled(user.isEnabled());
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
index c86885dd4f..f259177529 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/dto/AdminUserSummary.java
@@ -47,6 +47,10 @@ public class AdminUserSummary {
@Schema(description = "Authentication type (WEB, OAUTH2, SAML2)")
private String authenticationType;
+ /** Also the user's avatar storage path prefix. Null outside SaaS. */
+ @Schema(description = "Supabase auth id")
+ private String supabaseId;
+
@Schema(description = "Team membership (if any)")
private TeamSummary team;
diff --git a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
index 2a8ba71b6c..e2758cb4d7 100644
--- a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
+++ b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java
@@ -3,6 +3,7 @@ package stirling.software.saas.controller;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Profile;
@@ -311,9 +312,7 @@ public class SaasTeamController {
public ResponseEntity<?> getTeamMembers(@PathVariable Long teamId) {
try {
List<TeamMembership> memberships = membershipRepository.findByTeamId(teamId);
- List<TeamMemberDTO> dtos =
- memberships.stream().map(this::toTeamMemberDTO).collect(Collectors.toList());
- return ResponseEntity.ok(dtos);
+ return ResponseEntity.ok(toTeamMemberDTOs(memberships));
} catch (Exception e) {
log.error("Error fetching team members", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
@@ -499,14 +498,20 @@ public class SaasTeamController {
.orElseThrow(() -> new SecurityException("User not found: " + username));
}
+ private List<TeamMemberDTO> toTeamMemberDTOs(List<TeamMembership> memberships) {
+ return memberships.stream().map(this::toTeamMemberDTO).collect(Collectors.toList());
+ }
+
private TeamMemberDTO toTeamMemberDTO(TeamMembership membership) {
User user = membership.getUser();
+ UUID supabaseId = user.getSupabaseId();
return new TeamMemberDTO(
user.getId(),
user.getUsername(),
user.getEmail(),
membership.getRole().name(),
- membership.getAcceptedAt());
+ membership.getAcceptedAt(),
+ supabaseId == null ? null : supabaseId.toString());
}
private TeamDetailsDTO toTeamDetailsDTO(Team team, boolean isLeader) {
@@ -551,6 +556,9 @@ public class SaasTeamController {
private final String email;
private final String role;
private final LocalDateTime joinedAt;
+
+ /** Also the member's avatar storage path prefix. Null without a Supabase identity. */
+ private final String supabaseId;
}
@Data
@@ -673,8 +681,7 @@ public class SaasTeamController {
.orElseThrow(() -> new IllegalArgumentException("Team not found"));
List<TeamMembership> memberships = membershipRepository.findByTeamId(teamId);
- List<TeamMemberDTO> members =
- memberships.stream().map(this::toTeamMemberDTO).collect(Collectors.toList());
+ List<TeamMemberDTO> members = toTeamMemberDTOs(memberships);
// Check if current user is team leader
User currentUser = getCurrentUser();
diff --git a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
index f4bd636e46..d6ccdb3f7b 100644
--- a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java
@@ -710,6 +710,42 @@ class SaasTeamControllerTest {
assertThat(dtos.get(0).getRole()).isEqualTo("MEMBER");
}
+ @Test
+ @DisplayName("carries the Supabase id the browser needs to sign the avatar")
+ void exposesSupabaseId() {
+ Team team = team(10L, "Acme");
+ User bob = user(2L, "bob", "[email protected]");
+ java.util.UUID bobSupabaseId = java.util.UUID.randomUUID();
+ bob.setSupabaseId(bobSupabaseId);
+ when(membershipRepository.findByTeamId(10L))
+ .thenReturn(List.of(membership(team, bob, TeamRole.MEMBER)));
+
+ ResponseEntity<?> response = controller.getTeamMembers(10L);
+
+ @SuppressWarnings("unchecked")
+ List<SaasTeamController.TeamMemberDTO> dtos =
+ (List<SaasTeamController.TeamMemberDTO>) response.getBody();
+ assertThat(dtos.get(0).getSupabaseId()).isEqualTo(bobSupabaseId.toString());
+ }
+
+ @Test
+ @DisplayName("a member with no Supabase identity reports a null id")
+ void memberWithoutSupabaseIdIsNull() {
+ Team team = team(10L, "Acme");
+ when(membershipRepository.findByTeamId(10L))
+ .thenReturn(
+ List.of(
+ membership(
+ team, user(2L, "bob", "[email protected]"), TeamRole.MEMBER)));
+
+ ResponseEntity<?> response = controller.getTeamMembers(10L);
+
+ @SuppressWarnings("unchecked")
+ List<SaasTeamController.TeamMemberDTO> dtos =
+ (List<SaasTeamController.TeamMemberDTO>) response.getBody();
+ assertThat(dtos.get(0).getSupabaseId()).isNull();
+ }
+
@Test
@DisplayName("repository failure maps to 500")
void repoFailure_isServerError() {
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
index d5684f3c39..7be809b960 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/TeamSection.tsx
@@ -8,6 +8,7 @@ import {
Table,
Badge,
Menu,
+ Avatar,
} from "@mantine/core";
import { Button } from "@app/ui/Button";
import { ActionIcon } from "@app/ui/ActionIcon";
@@ -25,6 +26,7 @@ import {
type CloudOwnershipStatus,
} from "@app/components/shared/ownership/OwnershipTransferModal";
import apiClient from "@app/services/apiClient";
+import { useTeamAvatarUrls } from "@app/hooks/useTeamAvatarUrls";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@@ -377,16 +379,27 @@ function MemberActionsMenu({
interface TeamMemberRowProps extends MemberActionsMenuProps {
showActions: boolean;
+ /** Signed avatar URL; absent members fall back to their initial. */
+ avatarUrl?: string;
}
-function TeamMemberRow({ showActions, ...actions }: TeamMemberRowProps) {
+function TeamMemberRow({
+ showActions,
+ avatarUrl,
+ ...actions
+}: TeamMemberRowProps) {
const { member } = actions;
return (
<Table.Tr>
<Table.Td>
- <Text size="sm" fw={500}>
- {member.username}
- </Text>
+ <Group gap="xs" wrap="nowrap">
+ <Avatar size={28} radius="xl" src={avatarUrl} alt="" color="blue">
+ {member.username.charAt(0).toUpperCase()}
+ </Avatar>
+ <Text size="sm" fw={500}>
+ {member.username}
+ </Text>
+ </Group>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
@@ -468,6 +481,7 @@ function TeamMemberRows({
onCancelInvitation,
}: TeamMembersTableProps) {
const { t } = useTranslation();
+ const avatarUrls = useTeamAvatarUrls(members);
if (members.length === 0 && invitations.length === 0) {
return (
<Table.Tr>
@@ -485,6 +499,9 @@ function TeamMemberRows({
<TeamMemberRow
key={`member-${member.id}`}
member={member}
+ avatarUrl={
+ member.supabaseId ? avatarUrls[member.supabaseId] : undefined
+ }
showActions={showActions}
onMakeOwner={() => onMakeOwner(member)}
onRemove={() => onRemove(member)}
diff --git a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
index 9f01eebcb1..d5ae7995f2 100644
--- a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
+++ b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx
@@ -38,6 +38,8 @@ interface TeamMember {
email: string;
role: string;
joinedAt: string;
+ /** Also the member's avatar storage path prefix. */
+ supabaseId?: string | null;
}
interface TeamInvitation {
diff --git a/frontend/editor/src/portal/api/users.ts b/frontend/editor/src/portal/api/users.ts
index aac680f4e5..9bddb8cdc2 100644
--- a/frontend/editor/src/portal/api/users.ts
+++ b/frontend/editor/src/portal/api/users.ts
@@ -37,6 +37,8 @@ export interface Member {
lastActive: string;
/** Optional avatar image; falls back to initials when absent. */
avatarUrl?: string;
+ /** Also the member's avatar storage path prefix. */
+ supabaseId?: string | null;
/** Backend linkage for row actions (absent on pure fixtures). */
username?: string;
teamId?: number;
@@ -228,6 +230,7 @@ interface AdminUserSummaryDto {
isFirstLogin?: boolean;
team?: { id: number; name: string };
authenticationType?: string;
+ supabaseId?: string | null;
/** Authoritative server-side portal access (honors the configured default policy). */
portalAccess?: boolean;
}
@@ -307,6 +310,7 @@ export async function fetchUsers(tier: Tier): Promise<UsersResponse> {
locked: locked.has(u.username),
mfaEnabled: data.userSettings?.[u.username]?.mfaEnabled === "true",
authType: u.authenticationType,
+ supabaseId: u.supabaseId,
authority: u.rolesAsString,
}));
const seatLimit = normalizeSeatLimit(data.maxAllowedUsers);
diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
index eb4335525e..1037ce2b8a 100644
--- a/frontend/editor/src/portal/components/users/UsersDirectory.tsx
+++ b/frontend/editor/src/portal/components/users/UsersDirectory.tsx
@@ -20,6 +20,7 @@ import { type Member, type RoleId } from "@portal/api/users";
import type { Team } from "@portal/api/teams";
import type { UsersCapabilities } from "@portal/api/usersCapabilities";
import { avatarToneForMember } from "@portal/components/users/format";
+import { useTeamAvatarUrls } from "@app/hooks/useTeamAvatarUrls";
/** Tab key standing for "no team filter". */
const ALL_TEAMS = "__all__";
@@ -202,6 +203,8 @@ export function UsersDirectory({
[members, t],
);
+ const avatarUrls = useTeamAvatarUrls(members);
+
const columns = useMemo<DataTableColumn<Member>[]>(() => {
const isOwner = (m: Member) =>
capabilities.adminRole ? m.orgOwner === true : m.teamLead === true;
@@ -284,7 +287,15 @@ export function UsersDirectory({
key: "person",
header: t("users.columns.person", "Person"),
icon: (m) => (
- <Avatar name={m.name} size="sm" tone={avatarToneForMember(m)} />
+ <Avatar
+ name={m.name}
+ size="sm"
+ src={
+ m.avatarUrl ??
+ (m.supabaseId ? avatarUrls[m.supabaseId] : undefined)
+ }
+ tone={avatarToneForMember(m)}
+ />
),
primary: (m) => m.name,
suffix: (m) => (m.isSelf ? t("users.you", "(you)") : undefined),
@@ -466,6 +477,7 @@ export function UsersDirectory({
capabilities,
roleOptions,
members,
+ avatarUrls,
teams,
showApprover,
showEmail,
diff --git a/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.test.ts b/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.test.ts
new file mode 100644
index 0000000000..fdc03aca46
--- /dev/null
+++ b/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.test.ts
@@ -0,0 +1,162 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const client = vi.hoisted(() => ({
+ configured: true,
+ session: { user: { id: "viewer" } } as unknown,
+ createSignedUrls: vi.fn(),
+}));
+
+vi.mock("@app/services/supabaseClient", () => ({
+ get isSupabaseConfigured() {
+ return client.configured;
+ },
+ supabase: {
+ auth: {
+ getSession: () => Promise.resolve({ data: { session: client.session } }),
+ },
+ storage: { from: () => ({ createSignedUrls: client.createSignedUrls }) },
+ },
+}));
+
+import { useTeamAvatarUrls } from "@app/hooks/useTeamAvatarUrls";
+
+const ALICE = "11111111-1111-4111-8111-111111111111";
+const BOB = "22222222-2222-4222-8222-222222222222";
+
+/** The shape supabase-js returns: per-path outcomes inside a success. */
+function signed(entries: Array<[string, string | null]>) {
+ return {
+ data: entries.map(([id, url]) => ({
+ path: `${id}/avatar`,
+ signedUrl: url,
+ })),
+ error: null,
+ };
+}
+
+describe("useTeamAvatarUrls", () => {
+ beforeEach(() => {
+ client.configured = true;
+ client.session = { user: { id: "viewer" } };
+ client.createSignedUrls.mockReset();
+ client.createSignedUrls.mockResolvedValue(signed([]));
+ });
+
+ it("keys signed urls by supabase id", async () => {
+ client.createSignedUrls.mockResolvedValue(
+ signed([
+ [ALICE, "https://sb/alice?token=a"],
+ [BOB, null],
+ ]),
+ );
+
+ const { result } = renderHook(() =>
+ useTeamAvatarUrls([{ supabaseId: ALICE }, { supabaseId: BOB }]),
+ );
+
+ await waitFor(() =>
+ expect(result.current).toEqual({ [ALICE]: "https://sb/alice?token=a" }),
+ );
+ expect(client.createSignedUrls).toHaveBeenCalledWith(
+ [`${ALICE}/avatar`, `${BOB}/avatar`],
+ 3600,
+ );
+ });
+
+ it("does not re-sign when a poll returns the same members", async () => {
+ client.createSignedUrls.mockResolvedValue(
+ signed([[ALICE, "https://sb/alice"]]),
+ );
+ const members = [{ supabaseId: ALICE }];
+
+ const { result, rerender } = renderHook(
+ (m: typeof members) => useTeamAvatarUrls(m),
+ { initialProps: members },
+ );
+ await waitFor(() => expect(result.current[ALICE]).toBeDefined());
+
+ // A fresh array of the same ids, which is what each roster poll produces.
+ rerender([{ supabaseId: ALICE }]);
+ await waitFor(() => expect(result.current[ALICE]).toBeDefined());
+
+ expect(client.createSignedUrls).toHaveBeenCalledTimes(1);
+ });
+
+ it("signs again when the roster gains a member", async () => {
+ client.createSignedUrls.mockResolvedValue(
+ signed([[ALICE, "https://sb/alice"]]),
+ );
+ const { result, rerender } = renderHook(
+ (m: Array<{ supabaseId: string }>) => useTeamAvatarUrls(m),
+ { initialProps: [{ supabaseId: ALICE }] },
+ );
+ await waitFor(() => expect(result.current[ALICE]).toBeDefined());
+
+ client.createSignedUrls.mockResolvedValue(
+ signed([
+ [ALICE, "https://sb/alice"],
+ [BOB, "https://sb/bob"],
+ ]),
+ );
+ rerender([{ supabaseId: ALICE }, { supabaseId: BOB }]);
+
+ await waitFor(() => expect(result.current[BOB]).toBe("https://sb/bob"));
+ expect(client.createSignedUrls).toHaveBeenCalledTimes(2);
+ });
+
+ it("never sends an id that is not a bare uuid", async () => {
+ const { result } = renderHook(() =>
+ useTeamAvatarUrls([
+ { supabaseId: "../../etc/passwd" },
+ { supabaseId: "" },
+ { supabaseId: null },
+ ]),
+ );
+
+ await waitFor(() => expect(result.current).toEqual({}));
+ expect(client.createSignedUrls).not.toHaveBeenCalled();
+ });
+
+ it("skips storage entirely when signed out", async () => {
+ client.session = null;
+
+ const { result } = renderHook(() =>
+ useTeamAvatarUrls([{ supabaseId: ALICE }]),
+ );
+
+ await waitFor(() => expect(result.current).toEqual({}));
+ expect(client.createSignedUrls).not.toHaveBeenCalled();
+ });
+
+ it("falls back to initials when supabase is unconfigured", async () => {
+ client.configured = false;
+
+ const { result } = renderHook(() =>
+ useTeamAvatarUrls([{ supabaseId: ALICE }]),
+ );
+
+ await waitFor(() => expect(result.current).toEqual({}));
+ expect(client.createSignedUrls).not.toHaveBeenCalled();
+ });
+
+ it("drops already-signed urls when a later signing is refused", async () => {
+ client.createSignedUrls.mockResolvedValue(
+ signed([[ALICE, "https://sb/alice"]]),
+ );
+ const { result, rerender } = renderHook(
+ (m: Array<{ supabaseId: string }>) => useTeamAvatarUrls(m),
+ { initialProps: [{ supabaseId: ALICE }] },
+ );
+ await waitFor(() => expect(result.current[ALICE]).toBe("https://sb/alice"));
+
+ // Losing access to the bucket surfaces as a refusal on the next sign.
+ client.createSignedUrls.mockResolvedValue({
+ data: null,
+ error: { message: "nope" },
+ });
+ rerender([{ supabaseId: ALICE }, { supabaseId: BOB }]);
+
+ await waitFor(() => expect(result.current).toEqual({}));
+ });
+});
diff --git a/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.ts b/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.ts
new file mode 100644
index 0000000000..226a56aa34
--- /dev/null
+++ b/frontend/editor/src/proprietary/hooks/useTeamAvatarUrls.ts
@@ -0,0 +1,105 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { supabase, isSupabaseConfigured } from "@app/services/supabaseClient";
+
+const PROFILE_BUCKET = "profile-pictures";
+const SIGNED_URL_TTL_SECONDS = 60 * 60;
+
+/** Re-sign well before expiry, so a long-lived roster never shows a dead image. */
+const REFRESH_INTERVAL_MS = 45 * 60 * 1000;
+
+/** Ids are interpolated into a storage path, so only a bare uuid is ever sent. */
+const SUPABASE_ID =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+interface HasSupabaseId {
+ supabaseId?: string | null;
+}
+
+/**
+ * Signed avatar URLs for a set of team members, keyed by Supabase id. Ids the bucket refuses are
+ * absent, so callers fall back to initials.
+ *
+ * Keys off the set of ids rather than the member array: rosters poll on a timer, and an
+ * unchanged roster must not re-sign on every tick.
+ */
+export function useTeamAvatarUrls(
+ members: readonly HasSupabaseId[],
+): Record<string, string> {
+ const [urls, setUrls] = useState<Record<string, string>>({});
+ const requestRef = useRef(0);
+
+ const idKey = useMemo(
+ () =>
+ members
+ .map((m) => m.supabaseId)
+ .filter((id): id is string => Boolean(id) && SUPABASE_ID.test(id!))
+ .sort()
+ .join(","),
+ [members],
+ );
+
+ useEffect(() => {
+ if (!idKey || !isSupabaseConfigured || !supabase) {
+ setUrls({});
+ return;
+ }
+
+ const client = supabase;
+ const ids = idKey.split(",");
+ let cancelled = false;
+
+ const sign = async () => {
+ const request = ++requestRef.current;
+ try {
+ // The bucket is private and RLS keys off auth.uid(), so signing while signed out is
+ // refused every time. Skipping it also keeps tests off the network.
+ const { data: auth } = await client.auth.getSession();
+ if (cancelled || request !== requestRef.current) return;
+ if (!auth?.session) {
+ setUrls({});
+ return;
+ }
+
+ const paths: string[] = [];
+ for (const id of ids) {
+ if (!SUPABASE_ID.test(id)) {
+ throw new Error("Refusing to sign a non-uuid avatar path");
+ }
+ paths.push(`${id}/avatar`);
+ }
+
+ const { data, error } = await client.storage
+ .from(PROFILE_BUCKET)
+ .createSignedUrls(paths, SIGNED_URL_TTL_SECONDS);
+
+ if (cancelled || request !== requestRef.current) return;
+ if (error) {
+ // Drop what we held rather than keep serving it. A refusal is how losing access to
+ // the bucket shows up, so the safe reading of a failure is that these are no longer
+ // ours to show.
+ setUrls({});
+ return;
+ }
+
+ const next: Record<string, string> = {};
+ for (const entry of data ?? []) {
+ // Per-path outcome: a member with no stored picture carries an error and no signedUrl.
+ if (!entry.signedUrl || !entry.path?.endsWith("/avatar")) continue;
+ next[entry.path.slice(0, -"/avatar".length)] = entry.signedUrl;
+ }
+ setUrls(next);
+ } catch {
+ if (!cancelled) setUrls({});
+ }
+ };
+
+ void sign();
+ const timer = window.setInterval(() => void sign(), REFRESH_INTERVAL_MS);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [idKey]);
+
+ return urls;
+}