feat(notifications): add staff toggle to show only your own notifications
Staff with read-all oversight (superuser / system:admin-access) see everyone's notifications in the bell. Add a "Show all users" switch inside the dropdown, rendered only when the caller can view others, that narrows the feed to the caller's own notifications. The choice is remembered per browser (localStorage) and the unread badge follows the selected scope. The inbox route now reports canViewOthers and honors scope=all|mine; non-staff callers are always forced to their own regardless of the param.
This commit is contained in:
parent
0ed7524fdf
commit
37d7297b1a
3 changed files with 296 additions and 7 deletions
|
|
@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||||
import config from "@payload-config";
|
import config from "@payload-config";
|
||||||
import { getPayload } from "payload";
|
import { getPayload } from "payload";
|
||||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||||
|
import { hasPermission, isSuperuser } from "@/utils/access-control/hasPermission";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
|
|
@ -13,9 +14,16 @@ export const runtime = "nodejs";
|
||||||
* (/api/user-notifications) returns, but enriches every row with WHO it is
|
* (/api/user-notifications) returns, but enriches every row with WHO it is
|
||||||
* meant for (`ownerId` + `ownerName`) and whether it belongs to the caller
|
* meant for (`ownerId` + `ownerName`) and whether it belongs to the caller
|
||||||
* (`isMine`). Staff with read-all oversight see everyone's notifications, so
|
* (`isMine`). Staff with read-all oversight see everyone's notifications, so
|
||||||
* this is what lets the bell label "meant for someone else" rows. Read access
|
* this is what lets the bell label "meant for someone else" rows.
|
||||||
* is still scoped by the collection's own access control (own notifications for
|
*
|
||||||
* regular users, all for staff).
|
* Query:
|
||||||
|
* - `scope=all` (default) | `mine` — a caller with oversight (`canViewOthers`)
|
||||||
|
* may narrow the feed to just their own notifications. Non-staff are always
|
||||||
|
* scoped to their own, regardless of the param. The response echoes the
|
||||||
|
* effective `scope` plus `canViewOthers` so the bell can render its toggle.
|
||||||
|
*
|
||||||
|
* Read access is still scoped by the collection's own access control (own
|
||||||
|
* notifications for regular users, all for staff).
|
||||||
*/
|
*/
|
||||||
interface NotificationRow {
|
interface NotificationRow {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -37,6 +45,16 @@ export async function GET(req: NextRequest) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const userId = Number(user.id);
|
const userId = Number(user.id);
|
||||||
|
|
||||||
|
// Read-all oversight matches the collection's own read access: superusers
|
||||||
|
// and the `system:admin-access` tier. Everyone else only ever sees their own.
|
||||||
|
const canViewOthers =
|
||||||
|
(await isSuperuser(payload, user)) ||
|
||||||
|
(await hasPermission(payload, user, "system:admin-access"));
|
||||||
|
|
||||||
|
const requestedScope = req.nextUrl.searchParams.get("scope") === "mine" ? "mine" : "all";
|
||||||
|
const scope = canViewOthers ? requestedScope : "mine";
|
||||||
|
|
||||||
const res = await payload.find({
|
const res = await payload.find({
|
||||||
collection: "user-notifications",
|
collection: "user-notifications",
|
||||||
sort: "-createdAt",
|
sort: "-createdAt",
|
||||||
|
|
@ -44,6 +62,9 @@ export async function GET(req: NextRequest) {
|
||||||
depth: 1,
|
depth: 1,
|
||||||
overrideAccess: false,
|
overrideAccess: false,
|
||||||
user,
|
user,
|
||||||
|
// "Just mine" adds an explicit owner filter. When access already returns
|
||||||
|
// an ownership Where (non-staff) this simply ANDs with the same condition.
|
||||||
|
...(scope === "mine" ? { where: { user: { equals: userId } } } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const notifications = res.docs.map((doc) => {
|
const notifications = res.docs.map((doc) => {
|
||||||
|
|
@ -64,7 +85,7 @@ export async function GET(req: NextRequest) {
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ notifications });
|
return NextResponse.json({ notifications, canViewOthers, scope });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("notifications/inbox: failed to load", error);
|
console.error("notifications/inbox: failed to load", error);
|
||||||
return NextResponse.json({ error: "Failed to load notifications." }, { status: 500 });
|
return NextResponse.json({ error: "Failed to load notifications." }, { status: 500 });
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { BellIcon, CheckIcon } from "lucide-react";
|
import { BellIcon, CheckIcon } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
|
|
@ -52,6 +53,23 @@ function timeAgo(iso: string): string {
|
||||||
|
|
||||||
const POLL_MS = 60_000;
|
const POLL_MS = 60_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-browser memory of whether a staff user wants the bell to show everyone's
|
||||||
|
* notifications ("all") or only their own ("mine"). Non-staff are always
|
||||||
|
* scoped to their own server-side, so the value is irrelevant to them.
|
||||||
|
*/
|
||||||
|
const SCOPE_KEY = "ptf:notifications:scope";
|
||||||
|
type Scope = "all" | "mine";
|
||||||
|
|
||||||
|
function readStoredScope(): Scope {
|
||||||
|
if (typeof window === "undefined") return "all";
|
||||||
|
try {
|
||||||
|
return window.localStorage.getItem(SCOPE_KEY) === "mine" ? "mine" : "all";
|
||||||
|
} catch {
|
||||||
|
return "all";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function NotificationsBell() {
|
export function NotificationsBell() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||||
|
|
@ -60,25 +78,31 @@ export function NotificationsBell() {
|
||||||
const [error, setError] = useState(false);
|
const [error, setError] = useState(false);
|
||||||
const [actionError, setActionError] = useState<string | null>(null);
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
const [marking, setMarking] = useState(false);
|
const [marking, setMarking] = useState(false);
|
||||||
|
const [scope, setScope] = useState<Scope>(readStoredScope);
|
||||||
|
const [canViewOthers, setCanViewOthers] = useState(false);
|
||||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
|
|
||||||
const unreadCount = notifications.filter((n) => !n.read).length;
|
const unreadCount = notifications.filter((n) => !n.read).length;
|
||||||
|
|
||||||
const fetchNotifications = useCallback(async () => {
|
const fetchNotifications = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/notifications/inbox?limit=12&sort=-createdAt", {
|
const res = await fetch(`/api/notifications/inbox?limit=12&sort=-createdAt&scope=${scope}`, {
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error("Failed to fetch");
|
if (!res.ok) throw new Error("Failed to fetch");
|
||||||
const data = (await res.json()) as { notifications?: NotificationItem[] };
|
const data = (await res.json()) as {
|
||||||
|
notifications?: NotificationItem[];
|
||||||
|
canViewOthers?: boolean;
|
||||||
|
};
|
||||||
setNotifications(data.notifications ?? []);
|
setNotifications(data.notifications ?? []);
|
||||||
|
setCanViewOthers(Boolean(data.canViewOthers));
|
||||||
setError(false);
|
setError(false);
|
||||||
} catch {
|
} catch {
|
||||||
setError(true);
|
setError(true);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, []);
|
}, [scope]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void fetchNotifications();
|
void fetchNotifications();
|
||||||
|
|
@ -146,6 +170,16 @@ export function NotificationsBell() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleScopeToggle(next: boolean) {
|
||||||
|
const value: Scope = next ? "all" : "mine";
|
||||||
|
setScope(value);
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(SCOPE_KEY, value);
|
||||||
|
} catch {
|
||||||
|
// storage unavailable (private mode): the toggle still works this session
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
|
|
@ -177,6 +211,23 @@ export function NotificationsBell() {
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{canViewOthers && (
|
||||||
|
<div className="flex items-center justify-between gap-3 px-3 pb-2 pt-0.5">
|
||||||
|
<label htmlFor="notif-scope-all" className="cursor-pointer">
|
||||||
|
<span className="block text-xs font-medium">Show all users</span>
|
||||||
|
<span className="block text-[10px] text-muted-foreground">
|
||||||
|
{scope === "all" ? "You + everyone else" : "Only your notifications"}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<Switch
|
||||||
|
id="notif-scope-all"
|
||||||
|
size="sm"
|
||||||
|
checked={scope === "all"}
|
||||||
|
onCheckedChange={handleScopeToggle}
|
||||||
|
aria-label="Show notifications from all users"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<div className="max-h-96 overflow-y-auto">
|
<div className="max-h-96 overflow-y-auto">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
|
|
|
||||||
217
tests/int/notification-inbox-scope.int.spec.ts
Normal file
217
tests/int/notification-inbox-scope.int.spec.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
// @vitest-environment node
|
||||||
|
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
||||||
|
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
||||||
|
|
||||||
|
import { getFieldsToSign, getPayload, jwtSign, Payload } from "payload";
|
||||||
|
import config from "@/payload.config";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import type { Role, User } from "@/payload-types";
|
||||||
|
import type { Permission } from "@/permissions";
|
||||||
|
import { GET } from "@/app/api/notifications/inbox/route";
|
||||||
|
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
||||||
|
|
||||||
|
let payload: Payload;
|
||||||
|
|
||||||
|
const RUN = `ntfinbox-${Date.now().toString(36)}`;
|
||||||
|
const TIMEOUT = 30_000;
|
||||||
|
|
||||||
|
/** Build a GET against the inbox route, optionally authenticated + scoped. */
|
||||||
|
function request(token?: string, scope?: "all" | "mine"): NextRequest {
|
||||||
|
const headers = new Headers();
|
||||||
|
if (token) headers.set("cookie", `payload-token=${token}`);
|
||||||
|
const url = new URL("http://localhost/api/notifications/inbox");
|
||||||
|
url.searchParams.set("limit", "12");
|
||||||
|
url.searchParams.set("sort", "-createdAt");
|
||||||
|
if (scope) url.searchParams.set("scope", scope);
|
||||||
|
return new NextRequest(url, { headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mint a payload-token JWT for a user, mirroring the impersonation route:
|
||||||
|
* persist a session on the user doc, then sign with that session's sid.
|
||||||
|
*/
|
||||||
|
async function mintToken(userId: number): Promise<string> {
|
||||||
|
const collection = payload.collections.users.config;
|
||||||
|
const user = await payload.findByID({
|
||||||
|
collection: "users",
|
||||||
|
id: userId,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const sid = randomUUID();
|
||||||
|
const now = new Date();
|
||||||
|
const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000);
|
||||||
|
const sessions = (user.sessions ?? []).filter(
|
||||||
|
(session) => new Date(session.expiresAt).getTime() > now.getTime(),
|
||||||
|
);
|
||||||
|
sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() });
|
||||||
|
await payload.update({
|
||||||
|
collection: "users",
|
||||||
|
id: userId,
|
||||||
|
data: { sessions },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { token } = await jwtSign({
|
||||||
|
fieldsToSign: getFieldsToSign({
|
||||||
|
collectionConfig: collection,
|
||||||
|
email: user.email ?? "",
|
||||||
|
sid,
|
||||||
|
user,
|
||||||
|
}),
|
||||||
|
secret: payload.secret,
|
||||||
|
tokenExpiration: collection.auth.tokenExpiration,
|
||||||
|
});
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InboxBody {
|
||||||
|
notifications?: Array<{ id: number; isMine?: boolean; ownerName?: string }>;
|
||||||
|
canViewOthers?: boolean;
|
||||||
|
scope?: "all" | "mine";
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("notifications inbox scope toggle", () => {
|
||||||
|
const roleIds: number[] = [];
|
||||||
|
const userIds: number[] = [];
|
||||||
|
const notifIds: number[] = [];
|
||||||
|
|
||||||
|
let adminToken: string;
|
||||||
|
let plainToken: string;
|
||||||
|
let adminNotifId: number;
|
||||||
|
let plainNotifId: number;
|
||||||
|
|
||||||
|
const makeRole = async (label: string, permissions: Permission[]): Promise<Role> => {
|
||||||
|
const role = (await payload.create({
|
||||||
|
collection: "roles",
|
||||||
|
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, permissions },
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Role;
|
||||||
|
roleIds.push(role.id);
|
||||||
|
return role;
|
||||||
|
};
|
||||||
|
|
||||||
|
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||||
|
const user = (await payload.create({
|
||||||
|
collection: "users",
|
||||||
|
data: {
|
||||||
|
username: `${RUN}-${label}`,
|
||||||
|
discordUsername: `${RUN}-${label}`,
|
||||||
|
displayName: label.toUpperCase(),
|
||||||
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||||
|
password: "Test123",
|
||||||
|
roleDocs: [roleId],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as User;
|
||||||
|
userIds.push(user.id);
|
||||||
|
return user;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createNotification = async (userId: number): Promise<number> => {
|
||||||
|
const doc = await payload.create({
|
||||||
|
collection: "user-notifications",
|
||||||
|
data: {
|
||||||
|
user: userId,
|
||||||
|
type: "test:inbox-scope",
|
||||||
|
title: `${RUN} ${userId}`,
|
||||||
|
message: "test",
|
||||||
|
read: false,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
notifIds.push(doc.id as number);
|
||||||
|
return doc.id as number;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const payloadConfig = await config;
|
||||||
|
payload = await getPayload({ config: payloadConfig });
|
||||||
|
invalidatePermissionCache();
|
||||||
|
|
||||||
|
// The read-all tier is exactly `system:admin-access` (mirrors the collection
|
||||||
|
// access rule); a plain role (no permissions) only ever sees its own rows.
|
||||||
|
const adminRole = await makeRole("admin", ["system:admin-access"]);
|
||||||
|
const plainRole = await makeRole("plain", []);
|
||||||
|
const admin = await makeUser("admin", adminRole.id);
|
||||||
|
const plain = await makeUser("plain", plainRole.id);
|
||||||
|
|
||||||
|
adminNotifId = await createNotification(admin.id);
|
||||||
|
plainNotifId = await createNotification(plain.id);
|
||||||
|
|
||||||
|
adminToken = await mintToken(admin.id);
|
||||||
|
plainToken = await mintToken(plain.id);
|
||||||
|
invalidatePermissionCache();
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (!payload) return;
|
||||||
|
for (const id of notifIds) {
|
||||||
|
await payload.delete({ collection: "user-notifications", id, overrideAccess: true }).catch(
|
||||||
|
() => {},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const id of userIds) {
|
||||||
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of roleIds) {
|
||||||
|
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects unauthenticated callers", async () => {
|
||||||
|
const res = await GET(request());
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("admin scope=all sees both users' notifications and is told it can view others", async () => {
|
||||||
|
const res = await GET(request(adminToken, "all"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as InboxBody;
|
||||||
|
|
||||||
|
expect(body.canViewOthers).toBe(true);
|
||||||
|
expect(body.scope).toBe("all");
|
||||||
|
|
||||||
|
const ids = (body.notifications ?? []).map((n) => n.id);
|
||||||
|
expect(ids).toContain(adminNotifId);
|
||||||
|
expect(ids).toContain(plainNotifId);
|
||||||
|
|
||||||
|
const foreign = (body.notifications ?? []).find((n) => n.id === plainNotifId);
|
||||||
|
expect(foreign?.isMine).toBe(false);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("admin scope=mine narrows to just their own notifications", async () => {
|
||||||
|
const res = await GET(request(adminToken, "mine"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as InboxBody;
|
||||||
|
|
||||||
|
expect(body.canViewOthers).toBe(true);
|
||||||
|
expect(body.scope).toBe("mine");
|
||||||
|
|
||||||
|
const ids = (body.notifications ?? []).map((n) => n.id);
|
||||||
|
expect(ids).toContain(adminNotifId);
|
||||||
|
expect(ids).not.toContain(plainNotifId);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("plain user cannot view others and stays scoped to their own regardless of scope", async () => {
|
||||||
|
const res = await GET(request(plainToken, "all"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as InboxBody;
|
||||||
|
|
||||||
|
expect(body.canViewOthers).toBe(false);
|
||||||
|
// Requested "all" but the server forces "mine" for a non-oversight caller.
|
||||||
|
expect(body.scope).toBe("mine");
|
||||||
|
|
||||||
|
const ids = (body.notifications ?? []).map((n) => n.id);
|
||||||
|
expect(ids).toContain(plainNotifId);
|
||||||
|
expect(ids).not.toContain(adminNotifId);
|
||||||
|
}, TIMEOUT);
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue