mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-02 17:25:44 +00:00
Make some notifications be scoped to certain orgs to prevent redirect
issues.
This commit is contained in:
@@ -9,6 +9,7 @@ export async function up(knex: Knex): Promise<void> {
|
|||||||
.createTable(TableName.UserNotifications, (t) => {
|
.createTable(TableName.UserNotifications, (t) => {
|
||||||
t.uuid("id").defaultTo(knex.fn.uuid());
|
t.uuid("id").defaultTo(knex.fn.uuid());
|
||||||
t.uuid("userId").notNullable();
|
t.uuid("userId").notNullable();
|
||||||
|
t.uuid("orgId").nullable();
|
||||||
|
|
||||||
t.string("type").notNullable();
|
t.string("type").notNullable();
|
||||||
t.string("title").notNullable(); // Markdown
|
t.string("title").notNullable(); // Markdown
|
||||||
@@ -32,10 +33,11 @@ export async function up(knex: Knex): Promise<void> {
|
|||||||
|
|
||||||
await knex.schema.alterTable(TableName.UserNotifications, (t) => {
|
await knex.schema.alterTable(TableName.UserNotifications, (t) => {
|
||||||
t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
|
t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
|
||||||
|
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
|
||||||
|
|
||||||
t.index("type");
|
t.index("type");
|
||||||
t.index(["userId", "isRead"]);
|
t.index(["userId", "isRead"]);
|
||||||
t.index(["userId", "createdAt"]);
|
t.index(["userId", "createdAt", "orgId"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
await createOnUpdateTrigger(knex, TableName.UserNotifications);
|
await createOnUpdateTrigger(knex, TableName.UserNotifications);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { TImmutableDBKeys } from "./models";
|
|||||||
export const UserNotificationsSchema = z.object({
|
export const UserNotificationsSchema = z.object({
|
||||||
id: z.string().uuid(),
|
id: z.string().uuid(),
|
||||||
userId: z.string().uuid(),
|
userId: z.string().uuid(),
|
||||||
|
orgId: z.string().uuid().nullable().optional(),
|
||||||
type: z.string(),
|
type: z.string(),
|
||||||
title: z.string(),
|
title: z.string(),
|
||||||
body: z.string().nullable().optional(),
|
body: z.string().nullable().optional(),
|
||||||
|
|||||||
@@ -282,6 +282,7 @@ export const accessApprovalRequestServiceFactory = ({
|
|||||||
await notificationService.createUserNotifications(
|
await notificationService.createUserNotifications(
|
||||||
approverUsers.map((approver) => ({
|
approverUsers.map((approver) => ({
|
||||||
userId: approver.id,
|
userId: approver.id,
|
||||||
|
orgId: actorOrgId,
|
||||||
type: NotificationType.ACCESS_APPROVAL_REQUEST,
|
type: NotificationType.ACCESS_APPROVAL_REQUEST,
|
||||||
title: "Access Approval Request",
|
title: "Access Approval Request",
|
||||||
body: `**${requesterFullName}** (${requestedByUser.email}) has requested ${isTemporary ? "temporary" : "permanent"} access to **${secretPath}** in the **${envSlug}** environment for project **${project.name}**.`,
|
body: `**${requesterFullName}** (${requestedByUser.email}) has requested ${isTemporary ? "temporary" : "permanent"} access to **${secretPath}** in the **${envSlug}** environment for project **${project.name}**.`,
|
||||||
@@ -443,6 +444,7 @@ export const accessApprovalRequestServiceFactory = ({
|
|||||||
.filter((approver) => Boolean(approver.userId) && approver.userId !== editedByUser.id)
|
.filter((approver) => Boolean(approver.userId) && approver.userId !== editedByUser.id)
|
||||||
.map((approver) => ({
|
.map((approver) => ({
|
||||||
userId: approver.userId!,
|
userId: approver.userId!,
|
||||||
|
orgId: actorOrgId,
|
||||||
type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,
|
type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,
|
||||||
title: "Access Approval Request Updated",
|
title: "Access Approval Request Updated",
|
||||||
body: `**${editorFullName}** (${editedByUser.email}) has updated the access request submitted by **${requesterFullName}** (${requestedByUser.email}) for **${secretPath}** in the **${envSlug}** environment for project **${project.name}**.`,
|
body: `**${editorFullName}** (${editedByUser.email}) has updated the access request submitted by **${requesterFullName}** (${requestedByUser.email}) for **${secretPath}** in the **${envSlug}** environment for project **${project.name}**.`,
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ export const registerNotificationRouter = async (server: FastifyZodProvider) =>
|
|||||||
throw new UnauthorizedError({ message: "This endpoint can only be accessed by users" });
|
throw new UnauthorizedError({ message: "This endpoint can only be accessed by users" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const notifications = await server.services.notification.listUserNotifications({ userId: req.auth.userId });
|
const notifications = await server.services.notification.listUserNotifications({
|
||||||
|
userId: req.auth.userId,
|
||||||
|
orgId: req.auth.orgId
|
||||||
|
});
|
||||||
|
|
||||||
return { notifications };
|
return { notifications };
|
||||||
}
|
}
|
||||||
@@ -111,7 +114,10 @@ export const registerNotificationRouter = async (server: FastifyZodProvider) =>
|
|||||||
throw new UnauthorizedError({ message: "This endpoint can only be accessed by users" });
|
throw new UnauthorizedError({ message: "This endpoint can only be accessed by users" });
|
||||||
}
|
}
|
||||||
|
|
||||||
await server.services.notification.markUserNotificationsAsRead({ userId: req.auth.userId });
|
await server.services.notification.markUserNotificationsAsRead({
|
||||||
|
userId: req.auth.userId,
|
||||||
|
orgId: req.auth.orgId
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,13 +15,14 @@ export const notificationServiceFactory = ({
|
|||||||
notificationQueue,
|
notificationQueue,
|
||||||
userNotificationDAL
|
userNotificationDAL
|
||||||
}: TNotificationServiceFactoryDep) => {
|
}: TNotificationServiceFactoryDep) => {
|
||||||
const listUserNotifications = async ({ userId }: { userId: string }) => {
|
const listUserNotifications = async ({ userId, orgId }: { userId: string; orgId: string }) => {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const threeMonthsAgo = new Date();
|
const threeMonthsAgo = new Date();
|
||||||
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
|
||||||
|
|
||||||
const notifications = await userNotificationDAL.find({
|
const notifications = await userNotificationDAL.find({
|
||||||
userId,
|
userId,
|
||||||
|
orgId,
|
||||||
startDate: threeMonthsAgo.toISOString(),
|
startDate: threeMonthsAgo.toISOString(),
|
||||||
endDate: now.toISOString()
|
endDate: now.toISOString()
|
||||||
});
|
});
|
||||||
@@ -43,8 +44,8 @@ export const notificationServiceFactory = ({
|
|||||||
return deletedNotifications[0];
|
return deletedNotifications[0];
|
||||||
};
|
};
|
||||||
|
|
||||||
const markUserNotificationsAsRead = async ({ userId }: { userId: string }) => {
|
const markUserNotificationsAsRead = async ({ userId, orgId }: { userId: string; orgId: string }) => {
|
||||||
await userNotificationDAL.markAllNotificationsAsRead(userId);
|
await userNotificationDAL.markAllNotificationsAsRead(userId, orgId);
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateUserNotification = async ({
|
const updateUserNotification = async ({
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ export enum NotificationType {
|
|||||||
|
|
||||||
export interface TCreateUserNotificationDTO {
|
export interface TCreateUserNotificationDTO {
|
||||||
userId: string;
|
userId: string;
|
||||||
|
// Adding an orgId will make the notification only show up when a user is in a certain org. Otherwise, it shows up in all orgs.
|
||||||
|
// Keep in mind that org-scoped links for a notification will break if orgId is missing and the user is in the wrong org
|
||||||
|
orgId?: string;
|
||||||
type: NotificationType;
|
type: NotificationType;
|
||||||
title: string;
|
title: string;
|
||||||
body?: string;
|
body?: string;
|
||||||
|
|||||||
@@ -19,12 +19,14 @@ export const userNotificationDALFactory = (db: TDbClient) => {
|
|||||||
const find = async (
|
const find = async (
|
||||||
{
|
{
|
||||||
userId,
|
userId,
|
||||||
|
orgId,
|
||||||
startDate,
|
startDate,
|
||||||
endDate,
|
endDate,
|
||||||
limit = 1000,
|
limit = 1000,
|
||||||
offset = 0
|
offset = 0
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
|
orgId: string;
|
||||||
startDate: string;
|
startDate: string;
|
||||||
endDate: string;
|
endDate: string;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
@@ -35,6 +37,11 @@ export const userNotificationDALFactory = (db: TDbClient) => {
|
|||||||
try {
|
try {
|
||||||
const docs = await (tx || db.replicaNode())(TableName.UserNotifications)
|
const docs = await (tx || db.replicaNode())(TableName.UserNotifications)
|
||||||
.where(`${TableName.UserNotifications}.userId`, userId)
|
.where(`${TableName.UserNotifications}.userId`, userId)
|
||||||
|
.andWhere((qb) => {
|
||||||
|
void qb
|
||||||
|
.where(`${TableName.UserNotifications}.orgId`, orgId)
|
||||||
|
.orWhereNull(`${TableName.UserNotifications}.orgId`);
|
||||||
|
})
|
||||||
.whereRaw(`"${TableName.UserNotifications}"."createdAt" >= ?::timestamptz`, [startDate])
|
.whereRaw(`"${TableName.UserNotifications}"."createdAt" >= ?::timestamptz`, [startDate])
|
||||||
.andWhereRaw(`"${TableName.UserNotifications}"."createdAt" < ?::timestamptz`, [endDate])
|
.andWhereRaw(`"${TableName.UserNotifications}"."createdAt" < ?::timestamptz`, [endDate])
|
||||||
.select(selectAllTableCols(TableName.UserNotifications))
|
.select(selectAllTableCols(TableName.UserNotifications))
|
||||||
@@ -110,8 +117,13 @@ export const userNotificationDALFactory = (db: TDbClient) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const markAllNotificationsAsRead = async (userId: string) => {
|
const markAllNotificationsAsRead = async (userId: string, orgId: string) => {
|
||||||
await db(TableName.UserNotifications).where({ userId }).update({ isRead: true });
|
await db(TableName.UserNotifications)
|
||||||
|
.where({ userId })
|
||||||
|
.andWhere((qb) => {
|
||||||
|
void qb.where({ orgId }).orWhereNull("orgId");
|
||||||
|
})
|
||||||
|
.update({ isRead: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
return { ...notificationOrm, pruneNotifications, find, markAllNotificationsAsRead };
|
return { ...notificationOrm, pruneNotifications, find, markAllNotificationsAsRead };
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
|
import { useOrganization } from "@app/context";
|
||||||
|
|
||||||
import { notificationKeys } from "./queries";
|
import { notificationKeys } from "./queries";
|
||||||
import { TUserNotification } from "./types";
|
import { TUserNotification } from "./types";
|
||||||
|
|
||||||
export const useMarkAllNotificationsAsRead = () => {
|
export const useMarkAllNotificationsAsRead = () => {
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
|
const orgId = currentOrg.id || "";
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
await apiRequest.post("/api/v1/notifications/user/mark-as-read");
|
await apiRequest.post("/api/v1/notifications/user/mark-as-read");
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
|
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
|
||||||
if (!oldData) return oldData;
|
if (!oldData) return oldData;
|
||||||
return oldData.map((notification) => ({
|
return oldData.map((notification) => ({
|
||||||
...notification,
|
...notification,
|
||||||
@@ -24,6 +28,9 @@ export const useMarkAllNotificationsAsRead = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const useUpdateNotification = () => {
|
export const useUpdateNotification = () => {
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
|
const orgId = currentOrg.id || "";
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async ({ notificationId, isRead }: { notificationId: string; isRead: boolean }) => {
|
mutationFn: async ({ notificationId, isRead }: { notificationId: string; isRead: boolean }) => {
|
||||||
@@ -34,7 +41,7 @@ export const useUpdateNotification = () => {
|
|||||||
return data.notification;
|
return data.notification;
|
||||||
},
|
},
|
||||||
onSuccess: (updatedNotification) => {
|
onSuccess: (updatedNotification) => {
|
||||||
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
|
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
|
||||||
if (!oldData) return oldData;
|
if (!oldData) return oldData;
|
||||||
return oldData.map((notification) =>
|
return oldData.map((notification) =>
|
||||||
notification.id === updatedNotification.id ? updatedNotification : notification
|
notification.id === updatedNotification.id ? updatedNotification : notification
|
||||||
@@ -45,13 +52,16 @@ export const useUpdateNotification = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const useDeleteNotification = () => {
|
export const useDeleteNotification = () => {
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
|
const orgId = currentOrg.id || "";
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (notificationId: string) => {
|
mutationFn: async (notificationId: string) => {
|
||||||
await apiRequest.delete(`/api/v1/notifications/user/${notificationId}`);
|
await apiRequest.delete(`/api/v1/notifications/user/${notificationId}`);
|
||||||
},
|
},
|
||||||
onSuccess: (_, notificationId) => {
|
onSuccess: (_, notificationId) => {
|
||||||
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(), (oldData) => {
|
queryClient.setQueryData<TUserNotification[]>(notificationKeys.list(orgId), (oldData) => {
|
||||||
if (!oldData) return oldData;
|
if (!oldData) return oldData;
|
||||||
return oldData.filter((notification) => notification.id !== notificationId);
|
return oldData.filter((notification) => notification.id !== notificationId);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,17 +1,21 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
|
import { useOrganization } from "@app/context";
|
||||||
|
|
||||||
import { TUserNotification } from "./types";
|
import { TUserNotification } from "./types";
|
||||||
|
|
||||||
export const notificationKeys = {
|
export const notificationKeys = {
|
||||||
all: ["notifications"] as const,
|
all: ["notifications"] as const,
|
||||||
list: () => [...notificationKeys.all, "list"] as const
|
list: (orgId: string) => [...notificationKeys.all, "list", { orgId }] as const
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetMyNotifications = () => {
|
export const useGetMyNotifications = () => {
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
|
const orgId = currentOrg.id || "";
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: notificationKeys.list(),
|
queryKey: notificationKeys.list(orgId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const {
|
const {
|
||||||
data: { notifications }
|
data: { notifications }
|
||||||
|
|||||||
Reference in New Issue
Block a user