protect routes and import function

This commit is contained in:
Alex Holliday committed 2025-11-29 19:24:08 +00:00
1 parent e600f293b0
commit f476a57748
12 files changed
+112 -28

No files matched your search

-1
View File
@@ -3,7 +3,6 @@ import { encode, decode } from "@/utils/JWTUtils.js";
import AuthService from "@/services/business/AuthService.js";
import ApiError from "@/utils/ApiError.js";
import InviteService from "@/services/business/InviteService.js";
import { registerSchema } from "@/validation/index.js";
class AuthController {
private authService: AuthService;
private inviteService: InviteService;
+15 -5
View File
@@ -395,17 +395,27 @@ class MonitorController {
throw new ApiError("No organization ID", 400);
}
const result = await this.monitorService.import(
const entitlements = req.entitlements;
if (!entitlements) {
throw new ApiError("Entitlements not found", 500);
}
const result: any = await this.monitorService.import(
orgId,
teamId,
userContext.sub,
entitlements,
req.body
);
const defaultMessageMap: Record<string, string> = {
OK: `Imported ${result.imported} monitors`,
PARTIAL: `Imported ${result.imported} monitors, ${result.errors} skipped`,
NO_CAPACITY: `No capacity available. ${result.attempted} skipped`,
UNEXPECTED: `Import failed unexpectedly`,
};
res.status(200).json({
message: `Import request received. ${result.imported} successfully inserted, ${result.errors} failed`,
data: result,
});
const message = result?.message || defaultMessageMap[result?.code] || "Import completed";
res.status(result?.status ?? 200).json({ message, data: result });
try {
} catch (error) {
+6 -3
View File
@@ -1,3 +1,4 @@
import { PlanKey } from "@/types/entitlements.js";
import mongoose, { Schema, Document, Types } from "mongoose";
export type SubscriptionStatus =
| "active"
@@ -25,10 +26,11 @@ export interface IOrg extends Document {
cancelAtPeriodEnd?: boolean;
// Cached entitlements
entitlements?: {
entitlements: {
plan: PlanKey;
monitorsMax: number;
notificationChannelsMax: number;
statusPageMax: number;
statusPagesMax: number;
checksIntervalMsMin: number;
teamsMax: number;
notificationsEnabled: boolean;
@@ -62,9 +64,10 @@ const orgSchema = new Schema<IOrg>(
trialEnd: { type: Date },
cancelAtPeriodEnd: { type: Boolean },
entitlements: {
plan: { type: String },
monitorsMax: { type: Number },
notificationChannelsMax: { type: Number },
statusPageMax: { type: Number },
statusPagesMax: { type: Number },
checksIntervalMsMin: { type: Number },
teamsMax: { type: Number },
notificationsEnabled: { type: Boolean },
+3
View File
@@ -1,5 +1,6 @@
import mongoose, { Schema, Document, Types } from "mongoose";
import { IRole, ITeam } from "@/db/models/index.js";
import { Entitlements } from "@/types/entitlements.js";
export interface ITokenizedUser {
sub: string;
@@ -17,6 +18,7 @@ export interface IUserContext {
orgRole?: IRole;
teamRole: IRole;
};
entitlements: Entitlements;
}
export interface IUserReturnable {
@@ -33,6 +35,7 @@ export interface IUserReturnable {
name: string;
permissions: string[];
}[];
entitlements: Entitlements;
}
export interface IUser extends Document {
-1
View File
@@ -152,7 +152,6 @@ export const addUserContext = async (
const provider = EntitlementsFactory.create();
const entitlements: Entitlements = await provider.getForOrg(orgId);
req.entitlements = entitlements;
return next();
} catch (error) {
next(error);
+1 -1
View File
@@ -11,7 +11,7 @@ type NumberKeys<T> = {
}[keyof T];
const getEntitlements = (req: Request): Entitlements | undefined => {
return (req as any).entitlements as Entitlements | undefined;
return req.entitlements;
};
export const requireFeature = (flag: BooleanKeys<Entitlements>) => {
+4
View File
@@ -11,6 +11,7 @@ import { validateBody, validateQuery } from "@/middleware/validation.js";
import {
enforceMax,
enforceMinInterval,
requireFeature,
} from "@/middleware/VerifyEntitlements.js";
import { Monitor } from "@/db/models/index.js";
import {
@@ -86,6 +87,7 @@ class MonitorRoutes {
PERMISSIONS.monitors.read,
PERMISSIONS.notifications.read,
]),
requireFeature("notificationsEnabled"),
this.controller.testNotifications
);
@@ -111,6 +113,8 @@ class MonitorRoutes {
addUserContext,
verifyTeamPermission([PERMISSIONS.monitors.write]),
validateBody(monitorPatchSchema),
enforceMinInterval("checksIntervalMsMin", (req) => req.body.interval),
this.controller.update
);
+5 -1
View File
@@ -6,7 +6,7 @@ import { verifyTeamPermission } from "@/middleware/VerifyPermission.js";
import { addUserContext } from "@/middleware/AddUserContext.js";
import { PERMISSIONS } from "@/services/business/AuthService.js";
import { validateBody } from "@/middleware/validation.js";
import { enforceMax } from "@/middleware/VerifyEntitlements.js";
import { enforceMax, requireFeature } from "@/middleware/VerifyEntitlements.js";
import {
notificationChannelSchema,
notificationPatchSchema,
@@ -27,6 +27,7 @@ class NotificationChannelRoutes {
verifyToken,
addUserContext,
verifyTeamPermission([PERMISSIONS.notifications.write]),
requireFeature("notificationsEnabled"),
enforceMax("notificationChannelsMax", async (req: Request) =>
NotificationChannel.countDocuments({ orgId: req?.user?.orgId })
),
@@ -47,6 +48,7 @@ class NotificationChannelRoutes {
verifyToken,
addUserContext,
verifyTeamPermission([PERMISSIONS.notifications.write]),
requireFeature("notificationsEnabled"),
this.controller.toggleActive
);
@@ -55,6 +57,7 @@ class NotificationChannelRoutes {
verifyToken,
addUserContext,
verifyTeamPermission([PERMISSIONS.notifications.update]),
requireFeature("notificationsEnabled"),
validateBody(notificationPatchSchema),
this.controller.update
);
@@ -79,6 +82,7 @@ class NotificationChannelRoutes {
verifyToken,
addUserContext,
verifyTeamPermission([PERMISSIONS.notifications.write]),
requireFeature("notificationsEnabled"),
validateBody(notificationChannelSchema),
this.controller.test
);
+1 -1
View File
@@ -24,7 +24,7 @@ class StatusPageRoutes {
verifyToken,
addUserContext,
verifyTeamPermission([PERMISSIONS.statusPages.write]),
enforceMax("statusPageMax", async (req) =>
enforceMax("statusPagesMax", async (req) =>
StatusPage.countDocuments({ orgId: req?.user?.orgId })
),
validateBody(statusPageSchema),
+20 -1
View File
@@ -20,6 +20,7 @@ import { Types } from "mongoose";
import ApiError from "@/utils/ApiError.js";
import { IJobQueue } from "../infrastructure/JobQueue.js";
import { hashPassword } from "@/utils/JWTUtils.js";
import { Plans } from "@/types/entitlements.js";
const SERVICE_NAME = "AuthService";
@@ -206,6 +207,7 @@ class AuthService implements IAuthService {
permissions: orgRoles?.permissions || [],
},
teams: returnableTeams,
entitlements: org.entitlements,
};
return returnableUser;
@@ -237,6 +239,8 @@ class AuthService implements IAuthService {
const org = await Org.create({
name: `${user.firstName}'s Org`,
ownerId: user._id,
planKey: "free",
entitlements: Plans["free"],
});
created.org = org._id;
@@ -339,6 +343,7 @@ class AuthService implements IAuthService {
permissions: roles[0]?.permissions || [],
},
teams: [returnableTeam],
entitlements: org.entitlements,
};
return { tokenizedUser, returnableUser };
@@ -474,6 +479,7 @@ class AuthService implements IAuthService {
permissions: orgPermissions,
},
teams: returnableTeams,
entitlements: org.entitlements,
};
return {
@@ -522,12 +528,24 @@ class AuthService implements IAuthService {
}
// Find org and roles
const org = await Org.findById(orgMembership.orgId).lean();
let org = await Org.findById(orgMembership.orgId).lean();
if (!org) {
throw new ApiError("Organization not found");
}
// Update org entitlements
const planKey = org.entitlements.plan;
org = await Org.findOneAndUpdate(
{ _id: org._id },
{ $set: { entitlements: Plans[planKey] } },
{ new: true }
);
if (!org) {
throw new ApiError("Organization entitlement error");
}
const orgRoles = await Role.findById(orgMembership.roleId).lean();
// Get teams
@@ -567,6 +585,7 @@ class AuthService implements IAuthService {
permissions: orgRoles?.permissions || [],
},
teams: returnableTeams,
entitlements: org.entitlements,
};
return {
+50 -7
View File
@@ -5,6 +5,7 @@ import ApiError from "@/utils/ApiError.js";
import { IJobQueue } from "@/services/infrastructure/JobQueue.js";
import { MonitorWithChecksResponse } from "@/types/index.js";
import { MonitorStatus, MonitorType } from "@/db/models/monitors/Monitor.js";
import { Entitlements } from "@/types/entitlements.js";
export interface IImportedMonitor {
name: string;
@@ -65,6 +66,7 @@ export interface IMonitorService {
orgId: string,
teamId: string,
userId: string,
entitlements: Entitlements,
data: { monitors: Array<IImportedMonitor> }
) => Promise<{ imported: number; errors: number }>;
}
@@ -686,12 +688,35 @@ class MonitorService implements IMonitorService {
orgId: string,
teamId: string,
userId: string,
entitlements: Entitlements,
data: { monitors: Array<IImportedMonitor> }
) => {
let result = [];
const attempted = Array.isArray(data?.monitors) ? data.monitors.length : 0;
let result: IMonitor[] = [];
let canImport = 0;
try {
// Get current count
const monitorCount = await Monitor.countDocuments({ orgId });
// Check limits, return NO_CAPACITY if at limit
if (monitorCount >= entitlements.monitorsMax) {
return {
ok: true,
status: 200,
code: "NO_CAPACITY",
attempted,
eligible: 0,
imported: 0,
errors: attempted,
} as any;
}
// Proceed with import
canImport = entitlements.monitorsMax - monitorCount;
const importableMonitors = data?.monitors.slice(0, canImport);
result = await Monitor.insertMany(
data?.monitors.map((monitor) => ({
importableMonitors.map((monitor) => ({
...monitor,
orgId: new mongoose.Types.ObjectId(orgId),
teamId: new mongoose.Types.ObjectId(teamId),
@@ -703,14 +728,32 @@ class MonitorService implements IMonitorService {
for (const monitor of result) {
await this.jobQueue.addJob(monitor);
}
} catch (error) {
console.error("Import error:", error);
} catch (error: any) {
return {
ok: false,
status: 500,
code: "UNEXPECTED",
attempted,
eligible: canImport,
imported: result.length,
errors: Math.max(0, attempted - result.length),
message: error.message,
} as any;
}
const imported = result.length;
const errors = Math.max(0, attempted - imported);
const code = imported === attempted ? "OK" : "PARTIAL";
const status = imported === attempted ? 200 : 207;
return {
imported: result.length,
errors: data?.monitors?.length - result.length,
};
ok: true,
status,
code,
attempted,
eligible: canImport,
imported,
errors,
} as any;
};
}
+7 -7
View File
@@ -4,7 +4,7 @@ export interface Entitlements {
plan: PlanKey;
monitorsMax: number;
notificationChannelsMax: number;
statusPageMax: number;
statusPagesMax: number;
checksIntervalMsMin: number;
teamsMax: number;
notificationsEnabled: boolean;
@@ -14,9 +14,9 @@ export interface Entitlements {
export const Plans: Record<PlanKey, Entitlements> = {
free: {
plan: "free",
monitorsMax: 5,
monitorsMax: 3,
notificationChannelsMax: 2,
statusPageMax: 2,
statusPagesMax: 2,
checksIntervalMsMin: 60_000,
teamsMax: 2,
notificationsEnabled: true,
@@ -26,7 +26,7 @@ export const Plans: Record<PlanKey, Entitlements> = {
plan: "pro",
monitorsMax: 50,
notificationChannelsMax: 5,
statusPageMax: 5,
statusPagesMax: 5,
checksIntervalMsMin: 30_000,
teamsMax: 5,
notificationsEnabled: true,
@@ -36,7 +36,7 @@ export const Plans: Record<PlanKey, Entitlements> = {
plan: "business",
monitorsMax: 200,
notificationChannelsMax: 20,
statusPageMax: 20,
statusPagesMax: 20,
checksIntervalMsMin: 15_000,
teamsMax: 10,
notificationsEnabled: true,
@@ -46,7 +46,7 @@ export const Plans: Record<PlanKey, Entitlements> = {
plan: "enterprise",
monitorsMax: 5000,
notificationChannelsMax: 100,
statusPageMax: 100,
statusPagesMax: 100,
checksIntervalMsMin: 10_000,
teamsMax: 20,
notificationsEnabled: true,
@@ -56,7 +56,7 @@ export const Plans: Record<PlanKey, Entitlements> = {
plan: "unlimited",
monitorsMax: Number.MAX_SAFE_INTEGER,
notificationChannelsMax: Number.MAX_SAFE_INTEGER,
statusPageMax: Number.MAX_SAFE_INTEGER,
statusPagesMax: Number.MAX_SAFE_INTEGER,
checksIntervalMsMin: 1000,
teamsMax: Number.MAX_SAFE_INTEGER,
notificationsEnabled: true,