reorg to domain and api
This commit is contained in:
1 parent
0fb210e9e1
commit
d022f7d849
190 files changed
+643
-830
No files matched your search
Executable
+291
@@ -0,0 +1,291 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { requireTeamId, requireUserEmail, requireUserId, requireUserRoles } from "@/api/controllers/controllerUtils.js";
|
||||
|
||||
import {
|
||||
registrationBodyValidation,
|
||||
loginValidation,
|
||||
recoveryValidation,
|
||||
recoveryTokenBodyValidation,
|
||||
newPasswordValidation,
|
||||
} from "@/api/validation/authValidation.js";
|
||||
|
||||
import {
|
||||
editUserBodyValidation,
|
||||
createUserBodyValidation,
|
||||
getUserByIdParamValidation,
|
||||
editUserByIdParamValidation,
|
||||
editUserByIdBodyValidation,
|
||||
editSuperadminUserByIdBodyValidation,
|
||||
editUserPasswordByIdBodyValidation,
|
||||
} from "@/api/validation/userValidation.js";
|
||||
import { IUserService } from "@/domain/users/user.service.js";
|
||||
|
||||
const SERVICE_NAME = "authController";
|
||||
|
||||
export interface IAuthController {
|
||||
registerUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
createUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
loginUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
editUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
checkSuperadminExists(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
requestRecovery(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
validateRecovery(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
resetPassword(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
deleteUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
deleteUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
getAllUsers(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
getUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
editUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
editUserPasswordById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
}
|
||||
|
||||
class AuthController implements IAuthController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private userService: IUserService;
|
||||
|
||||
constructor(userService: IUserService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return AuthController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
registerUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const newUser = req.body.user;
|
||||
const newUserToken = req.body.token;
|
||||
if (newUser?.email) {
|
||||
const newUserEmail = requireUserEmail(newUser.email);
|
||||
newUser.email = newUserEmail.toLowerCase();
|
||||
}
|
||||
const validatedBody = registrationBodyValidation.parse(newUser);
|
||||
|
||||
const { user, token } = await this.userService.registerUser(validatedBody, newUserToken, req?.file ?? null);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: "User registered successfully",
|
||||
data: { user, token },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
createUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const userData = req.body;
|
||||
if (userData?.email) {
|
||||
userData.email = userData.email.toLowerCase();
|
||||
}
|
||||
const validatedBody = createUserBodyValidation.parse(userData);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const actorRoles = requireUserRoles(req.user?.role);
|
||||
const newUser = await this.userService.createUser(validatedBody, teamId, actorRoles, req?.file ?? null);
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
msg: "User created successfully",
|
||||
data: newUser,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
loginUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (req.body?.email) {
|
||||
req.body.email = req.body.email?.toLowerCase();
|
||||
}
|
||||
loginValidation.parse(req.body);
|
||||
const { user, token } = await this.userService.loginUser(req.body.email, req.body.password);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "User logged in successfully",
|
||||
data: {
|
||||
user,
|
||||
token,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = editUserBodyValidation.parse(req.body);
|
||||
const userId = requireUserId(req.user?.id);
|
||||
const userEmail = requireUserEmail(req.user?.email);
|
||||
const updatedUser = await this.userService.editUser(validatedBody, req?.file ?? null, userId, userEmail);
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: "User updated successfully",
|
||||
data: updatedUser,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
checkSuperadminExists = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const superAdminExists = await this.userService.checkSuperadminExists();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Superadmin existence checked successfully",
|
||||
data: superAdminExists,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
requestRecovery = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
recoveryValidation.parse(req.body);
|
||||
const email = req?.body?.email;
|
||||
const msgId = await this.userService.requestRecovery(email);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Password recovery email sent successfully",
|
||||
data: msgId,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
validateRecovery = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
recoveryTokenBodyValidation.parse(req.body);
|
||||
await this.userService.validateRecovery(req.body.recoveryToken);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Recovery token is valid",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
resetPassword = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
newPasswordValidation.parse(req.body);
|
||||
const { user, token } = await this.userService.resetPassword(req.body.password, req.body.recoveryToken);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Password has been reset successfully",
|
||||
data: { user, token },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const userId = requireUserId(req.user?.id);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const roles = requireUserRoles(req.user?.role);
|
||||
|
||||
await this.userService.deleteUser({
|
||||
userId,
|
||||
teamId,
|
||||
roles,
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "User deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getUserByIdParamValidation.parse(req.params);
|
||||
const targetUserId = validatedParams.userId;
|
||||
const actorId = requireUserId(req.user?.id);
|
||||
const actorTeamId = requireTeamId(req.user?.teamId);
|
||||
const actorRoles = requireUserRoles(req.user?.role);
|
||||
await this.userService.deleteUserById({ actorId, actorTeamId, actorRoles, targetUserId });
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "User removed successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getAllUsers = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const allUsers = await this.userService.getAllUsers();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Users retrieved successfully",
|
||||
data: allUsers,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getUserByIdParamValidation.parse(req.params);
|
||||
const actorRoles = requireUserRoles(req.user?.role);
|
||||
const user = await this.userService.getUserById(actorRoles, validatedParams.userId);
|
||||
|
||||
return res.status(200).json({ success: true, msg: "ok", data: user });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const actorRoles = requireUserRoles(req.user?.role);
|
||||
const actorId = requireUserId(req.user?.id);
|
||||
|
||||
if (!actorRoles.includes("superadmin")) {
|
||||
throw new AppError({ message: "Unauthorized", status: 403 });
|
||||
}
|
||||
|
||||
const validatedParams = editUserByIdParamValidation.parse(req.params);
|
||||
// If this is superadmin self edit, allow "superadmin" role
|
||||
const validatedBody =
|
||||
validatedParams.userId === actorId ? editSuperadminUserByIdBodyValidation.parse(req.body) : editUserByIdBodyValidation.parse(req.body);
|
||||
|
||||
await this.userService.editUserById(validatedParams.userId, validatedBody);
|
||||
return res.status(200).json({ success: true, msg: "ok" });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editUserPasswordById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const actorRoles = requireUserRoles(req.user?.role);
|
||||
if (!actorRoles.includes("superadmin")) {
|
||||
throw new AppError({ message: "Unauthorized", status: 403 });
|
||||
}
|
||||
|
||||
const validatedParams = editUserByIdParamValidation.parse(req.params);
|
||||
const validatedBody = editUserPasswordByIdBodyValidation.parse(req.body);
|
||||
await this.userService.setPasswordByUserId(validatedParams.userId, validatedBody.password);
|
||||
return res.status(200).json({ success: true, msg: "Password reset successfully" });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default AuthController;
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
import {
|
||||
getChecksParamValidation,
|
||||
getChecksQueryValidation,
|
||||
getTeamChecksQueryValidation,
|
||||
getChecksSummaryByTeamIdQueryValidation,
|
||||
deleteChecksParamValidation,
|
||||
} from "@/api/validation/checkValidation.js";
|
||||
import { ICheckService } from "@/domain/checks/check.service.js";
|
||||
import { requireTeamId } from "@/api/controllers/controllerUtils.js";
|
||||
|
||||
const SERVICE_NAME = "checkController";
|
||||
|
||||
export interface ICheckController {
|
||||
serviceName: string;
|
||||
getChecksByMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getChecksByTeam: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getChecksSummaryByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteChecks: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteChecksByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
|
||||
class CheckController implements ICheckController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private checkService: ICheckService;
|
||||
constructor(checkService: ICheckService) {
|
||||
this.checkService = checkService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return CheckController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getChecksParamValidation.parse(req.params);
|
||||
const validatedQuery = getChecksQueryValidation.parse(req.query);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const result = await this.checkService.getChecksByMonitor({
|
||||
monitorId: validatedParams.monitorId,
|
||||
teamId,
|
||||
sortOrder: validatedQuery.sortOrder,
|
||||
dateRange: validatedQuery.dateRange,
|
||||
filter: validatedQuery.filter,
|
||||
page: validatedQuery.page,
|
||||
rowsPerPage: validatedQuery.rowsPerPage,
|
||||
status: validatedQuery.status,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Checks retrieved successfully",
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getChecksByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getTeamChecksQueryValidation.parse(req.query);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const checkData = await this.checkService.getChecksByTeam({
|
||||
teamId,
|
||||
sortOrder: validatedQuery.sortOrder,
|
||||
dateRange: validatedQuery.dateRange,
|
||||
page: validatedQuery.page,
|
||||
rowsPerPage: validatedQuery.rowsPerPage,
|
||||
filter: validatedQuery.filter,
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Team checks retrieved successfully",
|
||||
data: checkData,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getChecksSummaryByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getChecksSummaryByTeamIdQueryValidation.parse(req.query);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const dateRange = validatedQuery.dateRange ?? "hour";
|
||||
|
||||
const summary = await this.checkService.getChecksSummaryByTeamId({ teamId, dateRange });
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Checks summary retrieved successfully",
|
||||
data: summary,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteChecks = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = deleteChecksParamValidation.parse(req.params);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const deletedCount = await this.checkService.deleteChecks({
|
||||
monitorId: validatedParams.monitorId,
|
||||
teamId,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Checks deleted successfully",
|
||||
data: { deletedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const deletedCount = await this.checkService.deleteChecksByTeamId({ teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Checks deleted successfully",
|
||||
data: { deletedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default CheckController;
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { Monitor, MonitorTypes, type MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { UserRole } from "@/domain/users/user.type.js";
|
||||
import sslChecker, { SSLDetails } from "ssl-checker";
|
||||
type SSLCheckerType = typeof sslChecker;
|
||||
|
||||
export const fetchMonitorCertificate = async (checker: SSLCheckerType, monitor: Monitor): Promise<SSLDetails> => {
|
||||
const monitorUrl = new URL(monitor.url);
|
||||
const hostname = monitorUrl.hostname;
|
||||
const cert = await checker(hostname);
|
||||
if (cert?.validTo === null || cert?.validTo === undefined) {
|
||||
throw new Error("Certificate not found");
|
||||
}
|
||||
return cert;
|
||||
};
|
||||
export const requireString = (value: unknown, fieldName: string): string => {
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
return value;
|
||||
}
|
||||
throw new AppError({ message: `${fieldName} is required`, status: 400 });
|
||||
};
|
||||
|
||||
export const optionalString = (value: unknown, fieldName: string): string | undefined => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
throw new AppError({ message: `${fieldName} must be a string`, status: 400 });
|
||||
};
|
||||
|
||||
export const extractString = (value: unknown): string | undefined => {
|
||||
const candidate = Array.isArray(value) ? value[0] : value;
|
||||
if (typeof candidate !== "string" || candidate.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
};
|
||||
|
||||
export const optionalNumber = (value: unknown, fieldName: string): number | undefined => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim() !== "") {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isNaN(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
throw new AppError({ message: `${fieldName} must be a number`, status: 400 });
|
||||
};
|
||||
|
||||
export const optionalBoolean = (value: unknown, fieldName: string): boolean | undefined => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
if (value === "true") {
|
||||
return true;
|
||||
}
|
||||
if (value === "false") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
throw new AppError({ message: `${fieldName} must be a boolean`, status: 400 });
|
||||
};
|
||||
|
||||
export const parseMonitorTypeFilter = (value: unknown): MonitorType | MonitorType[] | undefined => {
|
||||
const parseSingle = (input: unknown): MonitorType => {
|
||||
if (typeof input !== "string") {
|
||||
throw new AppError({ message: "Monitor type must be a string", status: 400 });
|
||||
}
|
||||
if (!MonitorTypes.includes(input as MonitorType)) {
|
||||
throw new AppError({ message: `Invalid monitor type: ${input}`, status: 400 });
|
||||
}
|
||||
return input as MonitorType;
|
||||
};
|
||||
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => parseSingle(entry));
|
||||
}
|
||||
return parseSingle(value);
|
||||
};
|
||||
|
||||
export const parseSortOrder = (value: unknown): "asc" | "desc" | undefined => {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (value === "asc" || value === "desc") {
|
||||
return value;
|
||||
}
|
||||
throw new AppError({ message: "order must be either 'asc' or 'desc'", status: 400 });
|
||||
};
|
||||
|
||||
export const requireTeamId = (teamId?: string): string => {
|
||||
if (!teamId) {
|
||||
throw new AppError({ message: "Team ID is required", status: 400 });
|
||||
}
|
||||
return teamId;
|
||||
};
|
||||
|
||||
export const requireUserId = (userId?: string): string => {
|
||||
if (!userId) {
|
||||
throw new AppError({ message: "User ID is required", status: 400 });
|
||||
}
|
||||
return userId;
|
||||
};
|
||||
export const requireUserEmail = (userEmail?: string): string => {
|
||||
if (!userEmail) {
|
||||
throw new AppError({ message: "User email is required", status: 400 });
|
||||
}
|
||||
return userEmail;
|
||||
};
|
||||
|
||||
export const requireFirstName = (firstName?: string): string => {
|
||||
if (!firstName) {
|
||||
throw new AppError({ message: "First name is required", status: 400 });
|
||||
}
|
||||
return firstName;
|
||||
};
|
||||
|
||||
export const requireUserRoles = (userRoles?: UserRole[]): UserRole[] => {
|
||||
if (!userRoles || userRoles.length === 0) {
|
||||
throw new AppError({ message: "User roles are required", status: 400 });
|
||||
}
|
||||
return userRoles;
|
||||
};
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { IDiagnosticService } from "@/domain/diagnostics/diagnostic.service.js";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
const SERVICE_NAME = "diagnosticController";
|
||||
|
||||
export interface IDiagnosticController {
|
||||
getSystemStats: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
|
||||
class DiagnosticController implements IDiagnosticController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private diagnosticService: IDiagnosticService;
|
||||
|
||||
constructor(diagnosticService: IDiagnosticService) {
|
||||
this.diagnosticService = diagnosticService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return DiagnosticController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getSystemStats = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const diagnostics = await this.diagnosticService.getSystemStats();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "OK",
|
||||
data: diagnostics,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default DiagnosticController;
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { getChecksParamValidation, getChecksQueryValidation } from "@/api/validation/checkValidation.js";
|
||||
import type { IGeoChecksService } from "@/domain/geo-checks/geo-check.service.js";
|
||||
import { requireTeamId } from "./controllerUtils.js";
|
||||
|
||||
const SERVICE_NAME = "geoCheckController";
|
||||
|
||||
export interface IGeoCheckController {
|
||||
getGeoChecksByMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
class GeoCheckController implements IGeoCheckController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private geoChecksService: IGeoChecksService;
|
||||
constructor(geoChecksService: IGeoChecksService) {
|
||||
this.geoChecksService = geoChecksService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return GeoCheckController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getGeoChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getChecksParamValidation.parse(req.params);
|
||||
const validatedQuery = getChecksQueryValidation.parse(req.query);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const result = await this.geoChecksService.getGeoChecksByMonitor({
|
||||
monitorId: validatedParams.monitorId,
|
||||
teamId: teamId,
|
||||
sortOrder: validatedQuery.sortOrder,
|
||||
dateRange: validatedQuery.dateRange,
|
||||
page: validatedQuery.page,
|
||||
rowsPerPage: validatedQuery.rowsPerPage,
|
||||
continent: validatedQuery.continent,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Geo checks retrieved successfully",
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default GeoCheckController;
|
||||
@@ -0,0 +1,107 @@
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { requireTeamId, requireUserId, requireUserEmail, extractString } from "./controllerUtils.js";
|
||||
import { IIncidentService } from "@/domain/incidents/incident.service.js";
|
||||
import { getIncidentsByTeamQueryValidation, getIncidentSummaryQueryValidation } from "@/api/validation/incidentValidation.js";
|
||||
|
||||
const SERVICE_NAME = "IncidentController";
|
||||
|
||||
export interface IIncidentController {
|
||||
getIncidentsByTeam: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getIncidentSummary: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getIncidentById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
resolveIncidentManually: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
class IncidentController implements IIncidentController {
|
||||
private incidentService: IIncidentService;
|
||||
constructor(incidentService: IIncidentService) {
|
||||
this.incidentService = incidentService;
|
||||
}
|
||||
|
||||
getIncidentsByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getIncidentsByTeamQueryValidation.parse(req.query);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const result = await this.incidentService.getIncidentsByTeam(
|
||||
teamId,
|
||||
validatedQuery.sortOrder,
|
||||
validatedQuery.dateRange,
|
||||
validatedQuery.page,
|
||||
validatedQuery.rowsPerPage,
|
||||
validatedQuery.status,
|
||||
validatedQuery.monitorId,
|
||||
validatedQuery.resolutionType
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Incidents retrieved successfully",
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getIncidentSummary = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const validatedQuery = getIncidentSummaryQueryValidation.parse(req.query);
|
||||
|
||||
const summary = await this.incidentService.getIncidentSummary(teamId, validatedQuery.limit);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Incident summary retrieved successfully",
|
||||
data: summary,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getIncidentById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const incidentId = req.params.incidentId as string;
|
||||
if (!incidentId) {
|
||||
throw new AppError({ message: "Incident ID is required", service: SERVICE_NAME, status: 400 });
|
||||
}
|
||||
|
||||
const incident = await this.incidentService.getIncidentById(incidentId, teamId);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Incident retrieved successfully",
|
||||
data: incident,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
resolveIncidentManually = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const userId = requireUserId(req.user?.id);
|
||||
const userEmail = requireUserEmail(req.user?.email);
|
||||
const incidentId = extractString(req.params?.incidentId);
|
||||
if (!incidentId) {
|
||||
throw new AppError({ message: "Incident ID is required", service: SERVICE_NAME, status: 400 });
|
||||
}
|
||||
|
||||
const comment = extractString(req.body?.comment);
|
||||
const resolvedIncident = await this.incidentService.resolveIncident(incidentId, userId, teamId, comment, userEmail);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Incident resolved successfully",
|
||||
data: resolvedIncident,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default IncidentController;
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { inviteBodyValidation, inviteVerificationBodyValidation } from "@/api/validation/authValidation.js";
|
||||
import { requireFirstName, requireTeamId, requireUserRoles } from "@/api/controllers/controllerUtils.js";
|
||||
import { IInviteService } from "@/domain/invites/invite.service.js";
|
||||
const SERVICE_NAME = "inviteController";
|
||||
|
||||
export interface IInviteController {
|
||||
getInviteToken: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
sendInviteEmail: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
verifyInviteToken: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
|
||||
class InviteController implements IInviteController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private inviteService: IInviteService;
|
||||
constructor(inviteService: IInviteService) {
|
||||
this.inviteService = inviteService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return InviteController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getInviteToken = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const userRoles = requireUserRoles(req.user?.role);
|
||||
const invite = req.body;
|
||||
invite.teamId = teamId;
|
||||
inviteBodyValidation.parse(invite);
|
||||
const inviteToken = await this.inviteService.getInviteToken({ invite, teamId, userRoles });
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Invite token generated successfully",
|
||||
data: inviteToken,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
sendInviteEmail = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const userRoles = requireUserRoles(req.user?.role);
|
||||
const firstName = requireFirstName(req.user?.firstName);
|
||||
|
||||
const inviteRequest = req.body;
|
||||
inviteRequest.teamId = teamId;
|
||||
inviteBodyValidation.parse(inviteRequest);
|
||||
|
||||
const inviteToken = await this.inviteService.sendInviteEmail({
|
||||
invite: inviteRequest,
|
||||
firstName,
|
||||
userRoles,
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Invite issued successfully",
|
||||
data: inviteToken,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
verifyInviteToken = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
inviteVerificationBodyValidation.parse(req.body);
|
||||
const invite = await this.inviteService.verifyInviteToken({ inviteToken: req?.body?.token });
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Invite verified successfully",
|
||||
data: invite,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default InviteController;
|
||||
@@ -0,0 +1,33 @@
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
const SERVICE_NAME = "LogController";
|
||||
|
||||
export interface ILogController {
|
||||
getLogs: (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
||||
}
|
||||
|
||||
class LogController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private logger: ILogger;
|
||||
constructor(logger: ILogger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
get serviceName() {
|
||||
return LogController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getLogs = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const logs = this.logger.getLogs();
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: "Logs fetched successfully",
|
||||
data: logs,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
export default LogController;
|
||||
@@ -0,0 +1,155 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import {
|
||||
createMaintenanceWindowBodyValidation,
|
||||
editMaintenanceWindowByIdParamValidation,
|
||||
editMaintenanceByIdWindowBodyValidation,
|
||||
getMaintenanceWindowByIdParamValidation,
|
||||
getMaintenanceWindowsByMonitorIdParamValidation,
|
||||
getMaintenanceWindowsByTeamIdQueryValidation,
|
||||
deleteMaintenanceWindowByIdParamValidation,
|
||||
} from "@/api/validation/maintenanceWindowValidation.js";
|
||||
import { requireTeamId } from "@/api/controllers/controllerUtils.js";
|
||||
import { IMaintenanceWindowService } from "@/domain/maintenance-windows/maintenance-window.service.js";
|
||||
|
||||
export interface IMaintenanceWindowController {
|
||||
createMaintenanceWindows: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMaintenanceWindowById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMaintenanceWindowsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMaintenanceWindowsByMonitorId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteMaintenanceWindow: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
editMaintenanceWindow: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
class MaintenanceWindowController implements IMaintenanceWindowController {
|
||||
private maintenanceWindowService: IMaintenanceWindowService;
|
||||
constructor(maintenanceWindowService: IMaintenanceWindowService) {
|
||||
this.maintenanceWindowService = maintenanceWindowService;
|
||||
}
|
||||
|
||||
createMaintenanceWindows = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = createMaintenanceWindowBodyValidation.parse(req.body);
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
|
||||
const monitorIDs = validatedBody.monitors;
|
||||
const name = validatedBody.name;
|
||||
const active = validatedBody.active ?? true;
|
||||
const duration = validatedBody.duration;
|
||||
const durationUnit = validatedBody.durationUnit;
|
||||
const repeat = validatedBody.repeat;
|
||||
const start = validatedBody.start;
|
||||
const end = validatedBody.end;
|
||||
|
||||
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, monitorIDs, name, active, duration, durationUnit, repeat, start, end });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance window created successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
getMaintenanceWindowById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const maintenanceWindow = await this.maintenanceWindowService.getMaintenanceWindowById({ id: validatedParams.id, teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance window fetched successfully",
|
||||
data: maintenanceWindow,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getMaintenanceWindowsByTeamIdQueryValidation.parse(req.query);
|
||||
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
|
||||
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByTeamId({
|
||||
teamId,
|
||||
active: validatedQuery.active,
|
||||
page: validatedQuery.page,
|
||||
rowsPerPage: validatedQuery.rowsPerPage,
|
||||
field: validatedQuery.field,
|
||||
order: validatedQuery.order,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance windows fetched successfully",
|
||||
data: maintenanceWindows,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMaintenanceWindowsByMonitorIdParamValidation.parse(req.params);
|
||||
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
|
||||
const maintenanceWindows = await this.maintenanceWindowService.getMaintenanceWindowsByMonitorId({
|
||||
monitorId: validatedParams.monitorId,
|
||||
teamId,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance windows fetched successfully",
|
||||
data: maintenanceWindows,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
deleteMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = deleteMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
|
||||
await this.maintenanceWindowService.deleteMaintenanceWindow({ id: validatedParams.id, teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance window deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editMaintenanceWindow = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = editMaintenanceWindowByIdParamValidation.parse(req.params);
|
||||
const validatedBody = editMaintenanceByIdWindowBodyValidation.parse(req.body);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const editedMaintenanceWindow = await this.maintenanceWindowService.editMaintenanceWindow({
|
||||
id: validatedParams.id,
|
||||
body: validatedBody,
|
||||
teamId,
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Maintenance window edited successfully",
|
||||
data: editedMaintenanceWindow,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default MaintenanceWindowController;
|
||||
@@ -0,0 +1,490 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { updateNotificationsValidation } from "@/api/validation/notificationValidation.js";
|
||||
import {
|
||||
getMonitorByIdParamValidation,
|
||||
getMonitorByIdQueryValidation,
|
||||
getMonitorsByTeamIdQueryValidation,
|
||||
getMonitorsWithChecksQueryValidation,
|
||||
createMonitorBodyValidation,
|
||||
editMonitorBodyValidation,
|
||||
pauseMonitorParamValidation,
|
||||
getCertificateParamValidation,
|
||||
getHardwareDetailsByIdParamValidation,
|
||||
getHardwareDetailsByIdQueryValidation,
|
||||
getUptimeDetailsByIdParamValidation,
|
||||
getUptimeDetailsByIdQueryValidation,
|
||||
importMonitorsBodyValidation,
|
||||
bulkPauseMonitorBodyValidation,
|
||||
} from "@/api/validation/monitorValidation.js";
|
||||
import sslChecker from "ssl-checker";
|
||||
import { fetchMonitorCertificate, requireTeamId, requireUserId } from "@/api/controllers/controllerUtils.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { IMonitorService } from "@/domain/monitors/monitor.service.js";
|
||||
import { INotificationsService } from "@/domain/notifications/notification.service.js";
|
||||
|
||||
const SERVICE_NAME = "monitorController";
|
||||
|
||||
export interface IMonitorController {
|
||||
getMonitorCertificate: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getUptimeDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getHardwareDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getPageSpeedDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getGeoChecksByMonitorId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMonitorById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
createMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
importMonitorsFromJSON: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteAllMonitors: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
editMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
pauseMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
bulkPauseMonitors: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
addDemoMonitors: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMonitorsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getMonitorsWithChecksByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
exportMonitorsToJSON: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getAllGames: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getGroupsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
updateNotifications: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
class MonitorController implements IMonitorController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private monitorService: IMonitorService;
|
||||
private notificationsService: INotificationsService;
|
||||
|
||||
constructor(monitorService: IMonitorService, notificationsService: INotificationsService) {
|
||||
this.monitorService = monitorService;
|
||||
this.notificationsService = notificationsService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return MonitorController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getMonitorCertificate = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getCertificateParamValidation.parse(req.params);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId: validatedParams.monitorId });
|
||||
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "SSL certificate retrieved successfully",
|
||||
data: {
|
||||
certificateDate: new Date(certificate.validTo),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getUptimeDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getUptimeDetailsByIdParamValidation.parse(req.params);
|
||||
const validatedQuery = getUptimeDetailsByIdQueryValidation.parse(req.query);
|
||||
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const dateRange = validatedQuery.dateRange;
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const data = await this.monitorService.getUptimeDetailsById({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Uptime details retrieved successfully",
|
||||
data: data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getHardwareDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getHardwareDetailsByIdParamValidation.parse(req.params);
|
||||
const validatedQuery = getHardwareDetailsByIdQueryValidation.parse(req.query);
|
||||
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const dateRange = validatedQuery.dateRange || "recent";
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const data = await this.monitorService.getHardwareDetailsById({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Hardware details retrieved successfully",
|
||||
data: data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
getPageSpeedDetailsById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getHardwareDetailsByIdParamValidation.parse(req.params);
|
||||
const validatedQuery = getHardwareDetailsByIdQueryValidation.parse(req.query);
|
||||
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const dateRange = validatedQuery.dateRange || "recent";
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const data = await this.monitorService.getPageSpeedDetailsById({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Page speed details retrieved successfully",
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getGeoChecksByMonitorId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
||||
const validatedQuery = getMonitorByIdQueryValidation.parse(req.query);
|
||||
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const dateRange = validatedQuery.dateRange || "recent";
|
||||
const continentParam = validatedQuery.continent;
|
||||
const continents = continentParam ? (Array.isArray(continentParam) ? continentParam : [continentParam]) : undefined;
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const data = await this.monitorService.getGeoChecksByMonitorId({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
continents,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Geo checks retrieved successfully",
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getMonitorById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const monitorId = validatedParams.monitorId;
|
||||
|
||||
const monitor = await this.monitorService.getMonitorById({ teamId, monitorId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitor retrieved successfully",
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
createMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = createMonitorBodyValidation.parse(req.body);
|
||||
|
||||
const userId = requireUserId(req.user?.id);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const monitor = await this.monitorService.createMonitor(teamId, userId, validatedBody);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitor created successfully",
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
importMonitorsFromJSON = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const userId = requireUserId(req.user?.id);
|
||||
const validatedBody = importMonitorsBodyValidation.parse(req.body);
|
||||
const monitors = validatedBody.monitors;
|
||||
|
||||
const result = await this.monitorService.importMonitorsFromJSON({ teamId, userId, monitors });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: `Successfully imported ${result.imported} monitor(s)`,
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const monitorId = validatedParams.monitorId;
|
||||
|
||||
const deletedMonitor = await this.monitorService.deleteMonitor({ teamId, monitorId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitor deleted successfully",
|
||||
data: deletedMonitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteAllMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const deletedCount = await this.monitorService.deleteAllMonitors({ teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: `Deleted ${deletedCount} monitors`,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
|
||||
const validatedBody = editMonitorBodyValidation.parse(req.body);
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: validatedBody });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitor edited successfully",
|
||||
data: editedMonitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
pauseMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedParams = pauseMonitorParamValidation.parse(req.params);
|
||||
|
||||
const monitorId = validatedParams.monitorId;
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const monitor = await this.monitorService.pauseMonitor({ teamId, monitorId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: monitor.isActive ? "Monitor resumed successfully" : "Monitor paused successfully",
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
bulkPauseMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = bulkPauseMonitorBodyValidation.parse(req.body);
|
||||
|
||||
const { monitorIds, pause } = validatedBody;
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const { monitors, failedCount } = await this.monitorService.bulkPauseMonitors({ teamId, monitorIds, pause });
|
||||
|
||||
const action = pause ? "paused" : "resumed";
|
||||
const monitorStr = monitors.length === 1 ? "monitor" : "monitors";
|
||||
|
||||
let msg = `${monitors.length} ${monitorStr} ${action} successfully`;
|
||||
if (failedCount > 0) {
|
||||
msg = `${monitors.length} ${monitorStr} ${action} in database, but ${failedCount} failed to sync with the job queue. Please check logs.`;
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg,
|
||||
data: { monitors, failedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
addDemoMonitors = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const id = requireUserId(req.user?.id);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const demoMonitors = await this.monitorService.addDemoMonitors({ userId: id, teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Demo monitors added successfully",
|
||||
data: demoMonitors?.length ?? 0,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getMonitorsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getMonitorsByTeamIdQueryValidation.parse(req.query);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const type = validatedQuery.type;
|
||||
const tags = validatedQuery.tags;
|
||||
const filter = validatedQuery.filter;
|
||||
|
||||
const monitors = await this.monitorService.getMonitorsByTeamId({ teamId, type, tags, filter });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitors retrieved successfully",
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getMonitorsWithChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedQuery = getMonitorsWithChecksQueryValidation.parse(req.query);
|
||||
|
||||
const limit = validatedQuery.limit;
|
||||
const page = validatedQuery.page;
|
||||
const rowsPerPage = validatedQuery.rowsPerPage;
|
||||
const filter = validatedQuery.filter;
|
||||
const field = validatedQuery.field;
|
||||
const order = validatedQuery.order;
|
||||
const type = validatedQuery.type;
|
||||
const tags = validatedQuery.tags;
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const monitors = await this.monitorService.getMonitorsWithChecksByTeamId({
|
||||
teamId,
|
||||
limit,
|
||||
type,
|
||||
tags,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
msg: "Monitors retrieved successfully",
|
||||
data: monitors,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
exportMonitorsToJSON = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const json = await this.monitorService.exportMonitorsToJSON({ teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Monitors exported successfully",
|
||||
data: json,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getAllGames = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const games = this.monitorService.getAllGames();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Supported games retrieved successfully",
|
||||
data: games,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getGroupsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const groups = await this.monitorService.getGroupsByTeamId({ teamId });
|
||||
|
||||
return res.status(200).json({
|
||||
msg: "Groups retrieved successfully",
|
||||
data: groups,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
updateNotifications = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
updateNotificationsValidation.parse(req.body);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const { monitorIds, notificationIds, action } = req.body;
|
||||
|
||||
// Verify all requested notification IDs actually belong to this team
|
||||
const teamNotifications = await this.notificationsService.findNotificationsByTeamId(teamId);
|
||||
const validNotificationIds = teamNotifications.map((n) => n.id);
|
||||
|
||||
const invalidIds = notificationIds.filter((id: string) => !validNotificationIds.includes(id));
|
||||
if (invalidIds.length > 0) {
|
||||
throw new AppError({
|
||||
message: `The following notification IDs are invalid or do not belong to your team: ${invalidIds.join(", ")}`,
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const modifiedCount = await this.monitorService.updateNotifications({
|
||||
teamId,
|
||||
monitorIds,
|
||||
notificationIds,
|
||||
action,
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: `Notifications updated successfully on ${modifiedCount} monitor(s)`,
|
||||
data: { modifiedCount },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default MonitorController;
|
||||
@@ -0,0 +1,163 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
import {
|
||||
createNotificationBodyValidation,
|
||||
deleteNotificationParamValidation,
|
||||
getNotificationByIdParamValidation,
|
||||
testNotificationBodyValidation,
|
||||
editNotificationParamValidation,
|
||||
testAllNotificationsBodyValidation,
|
||||
} from "@/api/validation/notificationValidation.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { INotificationsService } from "@/domain/notifications/notification.service.js";
|
||||
import { requireTeamId, requireUserId } from "./controllerUtils.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
|
||||
const SERVICE_NAME = "NotificationController";
|
||||
|
||||
export interface INotificationController {
|
||||
testNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
createNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getNotificationsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getNotificationById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
editNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
testAllNotifications: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
class NotificationController implements INotificationController {
|
||||
private notificationsService: INotificationsService;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
constructor(notificationsService: INotificationsService, monitorsRepository: IMonitorsRepository) {
|
||||
this.notificationsService = notificationsService;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
}
|
||||
|
||||
testNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const notification = testNotificationBodyValidation.parse(req.body);
|
||||
const success = await this.notificationsService.sendTestNotification(notification);
|
||||
|
||||
return res.status(200).json({
|
||||
success,
|
||||
msg: success ? "Notification sent successfully" : "Notification could not be sent — check the destination details.",
|
||||
details: { service: SERVICE_NAME },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
createNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = createNotificationBodyValidation.parse(req.body);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const userId = requireUserId(req.user?.id);
|
||||
|
||||
const notification = await this.notificationsService.createNotification(validatedBody, userId, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Notification created successfully",
|
||||
data: notification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getNotificationsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const notifications = await this.notificationsService.findNotificationsByTeamId(teamId);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Notifications fetched successfully",
|
||||
data: notifications,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const validatedParams = deleteNotificationParamValidation.parse(req.params);
|
||||
|
||||
await this.notificationsService.deleteById(validatedParams.id, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Notification deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getNotificationById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const validatedParams = getNotificationByIdParamValidation.parse(req.params);
|
||||
|
||||
const notification = await this.notificationsService.findById(validatedParams.id, teamId);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Notification fetched successfully",
|
||||
data: notification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editNotification = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = createNotificationBodyValidation.parse(req.body);
|
||||
const validatedParams = editNotificationParamValidation.parse(req.params);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const notificationId = validatedParams.id;
|
||||
|
||||
const editedNotification = await this.notificationsService.updateById(notificationId, teamId, validatedBody);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Notification updated successfully",
|
||||
data: editedNotification,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
testAllNotifications = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = testAllNotificationsBodyValidation.parse(req.body);
|
||||
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const monitor = await this.monitorsRepository.findById(validatedBody.monitorId, teamId);
|
||||
const notifications = monitor.notifications || [];
|
||||
|
||||
if (notifications.length === 0) {
|
||||
throw new AppError({ message: "No notifications", status: 400 });
|
||||
}
|
||||
|
||||
const result = await this.notificationsService.testAllNotifications(notifications);
|
||||
|
||||
if (!result) {
|
||||
throw new AppError({ message: "Failed to send all notifications", status: 500 });
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "All notifications sent successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default NotificationController;
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { IJobQueue } from "@/service/job-queues/job-queue.interface.js";
|
||||
import { getQueueJobsQueryValidation } from "@/api/validation/queueValidation.js";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
const SERVICE_NAME = "JobQueueController";
|
||||
|
||||
export interface IJobQueueController {
|
||||
getMetrics(req: Request, res: Response, next: NextFunction): Promise<void>;
|
||||
getJobs(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
getAllMetrics(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
flushQueue(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
}
|
||||
|
||||
class JobQueueController implements IJobQueueController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private jobQueue: IJobQueue;
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return JobQueueController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getMetrics = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: "Queue metrics fetched successfully",
|
||||
data: metrics,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getJobs = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const pagination = getQueueJobsQueryValidation.parse(req.query);
|
||||
const { jobs, count } = await this.jobQueue.getJobs(pagination);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Queue jobs fetched successfully",
|
||||
data: { jobs, count },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getAllMetrics = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const pagination = getQueueJobsQueryValidation.parse(req.query);
|
||||
const { jobs, count } = await this.jobQueue.getJobs(pagination);
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Queue metrics fetched successfully",
|
||||
data: { jobs, count, metrics },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
flushQueue = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const result = await this.jobQueue.flushQueues();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Queue flushed successfully",
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
export default JobQueueController;
|
||||
@@ -0,0 +1,143 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { updateAppSettingsBodyValidation } from "@/api/validation/settingsValidation.js";
|
||||
import { sendTestEmailBodyValidation } from "@/api/validation/notificationValidation.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { IEmailService } from "@/service/emailService.js";
|
||||
import { Settings } from "@/domain/app-settings/app-settings.type.js";
|
||||
|
||||
const SERVICE_NAME = "SettingsController";
|
||||
|
||||
export interface ISettingsController {
|
||||
serviceName: string;
|
||||
getAppSettings(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
updateAppSettings(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
sendTestEmail(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
}
|
||||
|
||||
class SettingsController implements ISettingsController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private settingsService: ISettingsService;
|
||||
private emailService: IEmailService;
|
||||
constructor(settingsService: ISettingsService, emailService: IEmailService) {
|
||||
this.settingsService = settingsService;
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return SettingsController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
buildAppSettings = (dbSettings: Settings) => {
|
||||
const sanitizedSettings: Record<string, unknown> = { ...dbSettings };
|
||||
delete sanitizedSettings.version;
|
||||
delete sanitizedSettings.jwtSecret;
|
||||
const returnSettings: Record<string, unknown | null> = {
|
||||
pagespeedKeySet: false,
|
||||
emailPasswordSet: false,
|
||||
settings: null,
|
||||
};
|
||||
|
||||
if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") {
|
||||
returnSettings.pagespeedKeySet = true;
|
||||
delete sanitizedSettings.pagespeedApiKey;
|
||||
}
|
||||
if (typeof sanitizedSettings.systemEmailPassword !== "undefined") {
|
||||
returnSettings.emailPasswordSet = true;
|
||||
delete sanitizedSettings.systemEmailPassword;
|
||||
}
|
||||
returnSettings.settings = sanitizedSettings;
|
||||
return returnSettings;
|
||||
};
|
||||
|
||||
getAppSettings = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
|
||||
const returnSettings = this.buildAppSettings(dbSettings);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "App settings fetched successfully",
|
||||
data: returnSettings,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
updateAppSettings = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = updateAppSettingsBodyValidation.parse(req.body);
|
||||
|
||||
const updatedSettings = await this.settingsService.updateDbSettings(validatedBody);
|
||||
const returnSettings = this.buildAppSettings(updatedSettings);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "App settings updated successfully",
|
||||
data: returnSettings,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
sendTestEmail = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
sendTestEmailBodyValidation.parse(req.body);
|
||||
|
||||
const {
|
||||
to,
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
systemEmailAddress,
|
||||
systemEmailDisplayName,
|
||||
systemEmailPassword,
|
||||
systemEmailUser,
|
||||
systemEmailConnectionHost,
|
||||
systemEmailSecure,
|
||||
systemEmailPool,
|
||||
systemEmailIgnoreTLS,
|
||||
systemEmailRequireTLS,
|
||||
systemEmailRejectUnauthorized,
|
||||
systemEmailTLSServername,
|
||||
} = req.body;
|
||||
|
||||
const subject = "This is a test email from Checkmate";
|
||||
const context = { testName: "Monitoring System" };
|
||||
|
||||
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||
if (!html) {
|
||||
throw new AppError({ message: "Failed to build email template.", status: 500 });
|
||||
}
|
||||
const messageId = await this.emailService.sendEmail(to, subject, html, {
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
systemEmailUser,
|
||||
systemEmailAddress,
|
||||
systemEmailDisplayName,
|
||||
systemEmailPassword,
|
||||
systemEmailConnectionHost,
|
||||
systemEmailSecure,
|
||||
systemEmailPool,
|
||||
systemEmailIgnoreTLS,
|
||||
systemEmailRequireTLS,
|
||||
systemEmailRejectUnauthorized,
|
||||
systemEmailTLSServername,
|
||||
});
|
||||
|
||||
if (!messageId) {
|
||||
throw new AppError({ message: "Failed to send test email.", status: 500 });
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Test email sent successfully",
|
||||
data: { messageId },
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default SettingsController;
|
||||
@@ -0,0 +1,173 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
import {
|
||||
createStatusPageBodyValidation,
|
||||
getStatusPageParamValidation,
|
||||
getStatusPageQueryValidation,
|
||||
imageValidation,
|
||||
} from "@/api/validation/statusPageValidation.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { requireTeamId, requireUserId } from "@/api/controllers/controllerUtils.js";
|
||||
import { IStatusPageService } from "@/domain/status-pages/status-page.service.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { NormalizeData } from "@/utils/dataUtils.js";
|
||||
|
||||
const SERVICE_NAME = "statusPageController";
|
||||
|
||||
export interface IStatusPageController {
|
||||
readonly serviceName: string;
|
||||
createStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
updateStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
getStatusPageByUrl(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
getStatusPagesByTeamId(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
deleteStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||
}
|
||||
|
||||
class StatusPageController implements IStatusPageController {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private statusPageService: IStatusPageService;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private settingsService: ISettingsService;
|
||||
constructor(statusPageService: IStatusPageService, monitorsRepository: IMonitorsRepository, settingsService: ISettingsService) {
|
||||
this.statusPageService = statusPageService;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.settingsService = settingsService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return StatusPageController.SERVICE_NAME;
|
||||
}
|
||||
|
||||
createStatusPage = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
createStatusPageBodyValidation.parse(req.body);
|
||||
if (req.file) {
|
||||
imageValidation.parse(req.file);
|
||||
}
|
||||
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
const userId = requireUserId(req?.user?.id);
|
||||
const statusPage = await this.statusPageService.createStatusPage(userId, teamId, req.file, req.body);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Status page created successfully",
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
updateStatusPage = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
createStatusPageBodyValidation.parse(req.body);
|
||||
if (req.file) {
|
||||
imageValidation.parse(req.file);
|
||||
}
|
||||
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
const statusPageId = req.params.id as string;
|
||||
if (!statusPageId) {
|
||||
throw new AppError({ message: "Status page ID is required", status: 400 });
|
||||
}
|
||||
const statusPage = await this.statusPageService.updateStatusPage(statusPageId, teamId, req.file, req.body);
|
||||
if (statusPage === null) {
|
||||
throw new AppError({ message: "Status page not found", status: 404 });
|
||||
}
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
msg: "Status page updated successfully",
|
||||
data: statusPage,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getStatusPageByUrl = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
getStatusPageParamValidation.parse(req.params);
|
||||
getStatusPageQueryValidation.parse(req.query);
|
||||
|
||||
if (!req.params.url) {
|
||||
throw new AppError({ message: "Status page URL is required", status: 400 });
|
||||
}
|
||||
|
||||
const statusPage = await this.statusPageService.getStatusPageByUrl(req.params.url as string);
|
||||
|
||||
if (!statusPage.isPublished) {
|
||||
const teamId = requireTeamId(req?.user?.teamId);
|
||||
if (statusPage.teamId !== teamId) {
|
||||
throw new AppError({ message: "Forbidden", status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
const settings = await this.settingsService.getDBSettings();
|
||||
const showURL = settings.showURL;
|
||||
|
||||
const monitors = await this.monitorsRepository.findByIds(statusPage.monitors);
|
||||
// Sort monitors according to the order in statusPage.monitors
|
||||
const monitorOrder = new Map(statusPage.monitors.map((id, index) => [id, index]));
|
||||
const sortedMonitors = [...monitors].sort((a, b) => {
|
||||
const orderA = monitorOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
const orderB = monitorOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
return orderA - orderB;
|
||||
});
|
||||
|
||||
const normalizedMonitors = sortedMonitors.map((monitor) => {
|
||||
const normalizedChecks = NormalizeData(monitor.recentChecks, 10, 100);
|
||||
if (!showURL) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { url, port, secret, notifications, ...rest } = monitor;
|
||||
return { ...rest, checks: normalizedChecks };
|
||||
}
|
||||
return { ...monitor, checks: normalizedChecks };
|
||||
});
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Status page retrieved successfully",
|
||||
data: {
|
||||
statusPage,
|
||||
monitors: normalizedMonitors,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
getStatusPagesByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const statusPages = await this.statusPageService.getStatusPagesByTeamId(teamId);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Status pages retrieved successfully",
|
||||
data: statusPages,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteStatusPage = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const statusPageId = req.params.id as string;
|
||||
if (!statusPageId) {
|
||||
throw new AppError({ message: "Status page ID is required", status: 400 });
|
||||
}
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
await this.statusPageService.deleteStatusPage(statusPageId, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Status page deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default StatusPageController;
|
||||
@@ -0,0 +1,33 @@
|
||||
import { DEFAULT_STATUS_PAGE_THEME, DEFAULT_STATUS_PAGE_THEME_MODE, type StatusPage } from "@/domain/status-pages/status-page.type.js";
|
||||
|
||||
/**
|
||||
* When STATUS_PAGE_THEMES_ENABLED is false, the controller drops incoming
|
||||
* theme fields before persisting so an admin client can't accidentally store
|
||||
* a value the public page won't honour. Whatever a caller sends here for
|
||||
* `theme` / `themeMode` is silently ignored — the rest of the body is
|
||||
* preserved verbatim.
|
||||
*
|
||||
* The strip is silent (not a 400) because the kill switch is an ops-side
|
||||
* concern: API clients should not have to know whether the operator has
|
||||
* disabled themes today, only that their saved value won't take effect.
|
||||
* If we later decide we'd rather fail loudly, change this to throw a
|
||||
* 400 AppError; downstream consumers already handle it.
|
||||
*/
|
||||
export const withoutThemeFields = (body: Record<string, unknown>): Record<string, unknown> => {
|
||||
const rest = { ...body };
|
||||
delete rest.theme;
|
||||
delete rest.themeMode;
|
||||
return rest;
|
||||
};
|
||||
|
||||
/**
|
||||
* When STATUS_PAGE_THEMES_ENABLED is false, callers reading a status page
|
||||
* should see the canonical default theme / mode regardless of what's stored
|
||||
* in Mongo. Whatever the user previously chose stays in the DB so flipping
|
||||
* the flag back on resurfaces their selection.
|
||||
*/
|
||||
export const applyDefaultTheme = (statusPage: StatusPage): StatusPage => ({
|
||||
...statusPage,
|
||||
theme: DEFAULT_STATUS_PAGE_THEME,
|
||||
themeMode: DEFAULT_STATUS_PAGE_THEME_MODE,
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { ITagsService } from "@/domain/tags/tag.service.js";
|
||||
import { requireTeamId } from "./controllerUtils.js";
|
||||
import {
|
||||
createTagBodyValidation,
|
||||
editTagBodyValidation,
|
||||
getTagByIdParamValidation,
|
||||
editTagParamValidation,
|
||||
deleteTagParamValidation,
|
||||
} from "@/api/validation/index.js";
|
||||
|
||||
export interface ITagsController {
|
||||
createTag: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getTagById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
getTagsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
editTag: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
deleteTag: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||
}
|
||||
|
||||
class TagsController implements ITagsController {
|
||||
constructor(private tagsService: ITagsService) {}
|
||||
|
||||
createTag = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const validatedBody = createTagBodyValidation.parse(req.body);
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
|
||||
const tag = await this.tagsService.createTag(validatedBody, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Tag created successfully",
|
||||
data: tag,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
getTagById = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const { id: tagId } = getTagByIdParamValidation.parse(req.params);
|
||||
const tag = await this.tagsService.getTag(tagId, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Tag retrieved successfully",
|
||||
data: tag,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
getTagsByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const tags = await this.tagsService.getTagsByTeamId(teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Tags retrieved successfully",
|
||||
data: tags,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
editTag = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const { id: tagId } = editTagParamValidation.parse(req.params);
|
||||
const validatedBody = editTagBodyValidation.parse(req.body);
|
||||
const updatedTag = await this.tagsService.updateTag(tagId, teamId, validatedBody);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Tag updated successfully",
|
||||
data: updatedTag,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
deleteTag = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const teamId = requireTeamId(req.user?.teamId);
|
||||
const { id: tagId } = deleteTagParamValidation.parse(req.params);
|
||||
await this.tagsService.deleteTag(tagId, teamId);
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
msg: "Tag deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default TagsController;
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import { logger } from "@/utils/logger.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
const handleErrors = (error: unknown, req: Request, res: Response, _next: NextFunction) => {
|
||||
const status = error instanceof AppError ? error.status || 500 : 500;
|
||||
const message = error instanceof AppError ? error.message : error instanceof Error ? error.message : "Server error";
|
||||
const service = error instanceof AppError ? error.service : "unknownService";
|
||||
const method = error instanceof AppError ? error.method : "unknownMethod";
|
||||
logger.error({
|
||||
message: message,
|
||||
service: service,
|
||||
method: method,
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
details: error instanceof AppError ? error.details : undefined,
|
||||
});
|
||||
res.status(status).json({
|
||||
status,
|
||||
msg: message,
|
||||
});
|
||||
};
|
||||
|
||||
export { handleErrors };
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
const SERVICE_NAME = "allowedRoles";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import type { UserRole } from "@/domain/users/user.type.js";
|
||||
|
||||
const isAllowed = (allowedRoles: UserRole[]) => {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const user = req.user;
|
||||
if (!user) {
|
||||
throw new AppError({ message: "Unauthorized", status: 403, service: SERVICE_NAME });
|
||||
}
|
||||
const userRoles = req.user?.role || [];
|
||||
|
||||
// Check if the user has the required role
|
||||
if (userRoles.some((role) => allowedRoles.includes(role))) {
|
||||
next();
|
||||
return;
|
||||
} else {
|
||||
throw new AppError({ message: "Unauthorized", status: 403, service: SERVICE_NAME });
|
||||
}
|
||||
} catch (error) {
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export { isAllowed };
|
||||
@@ -0,0 +1,17 @@
|
||||
import rateLimit from "express-rate-limit";
|
||||
|
||||
export const generalApiLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
limit: 600,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
ipv6Subnet: 64,
|
||||
});
|
||||
|
||||
export const authApiLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
limit: 15,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
ipv6Subnet: 64,
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import DOMPurify from "isomorphic-dompurify";
|
||||
|
||||
export function sanitizeInput(input: string, options?: object): string;
|
||||
export function sanitizeInput(input: unknown, options?: object): unknown;
|
||||
export function sanitizeInput(input: unknown, options = {}): unknown {
|
||||
if (typeof input !== "string") {
|
||||
return input;
|
||||
}
|
||||
|
||||
// Default configuration - remove all HTML tags and attributes
|
||||
const defaultConfig = {
|
||||
ALLOWED_TAGS: [] as string[],
|
||||
ALLOWED_ATTR: [] as string[],
|
||||
KEEP_CONTENT: true,
|
||||
...options,
|
||||
};
|
||||
|
||||
return DOMPurify.sanitize(input, defaultConfig);
|
||||
}
|
||||
|
||||
export const sanitizeObject = (obj: unknown, options = {}): unknown => {
|
||||
if (typeof obj !== "object" || obj === null) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => sanitizeObject(item, options));
|
||||
}
|
||||
|
||||
const sanitized: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (typeof value === "string") {
|
||||
sanitized[key] = sanitizeInput(value, options);
|
||||
} else if (typeof value === "object" && value !== null) {
|
||||
sanitized[key] = sanitizeObject(value, options);
|
||||
} else {
|
||||
sanitized[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
};
|
||||
|
||||
export const sanitizeBody = (options = {}): ((req: Request, res: Response, next: NextFunction) => void) => {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.body && typeof req.body === "object") {
|
||||
req.body = sanitizeObject(req.body, options);
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
export const sanitizeQuery = (options = {}): ((req: Request, res: Response, next: NextFunction) => void) => {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.query && typeof req.query === "object") {
|
||||
for (const key of Object.keys(req.query)) {
|
||||
const value = req.query[key];
|
||||
if (typeof value === "string") {
|
||||
req.query[key] = sanitizeInput(value, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
|
||||
import jwt from "jsonwebtoken";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import type { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import type { User } from "@/domain/users/user.type.js";
|
||||
|
||||
const SERVICE_NAME = "verifyJWT";
|
||||
const TOKEN_PREFIX = "Bearer ";
|
||||
|
||||
const isUser = (payload: unknown): payload is User => {
|
||||
return typeof payload === "object" && payload !== null && "id" in payload && "teamId" in payload && "role" in payload;
|
||||
};
|
||||
|
||||
export const createVerifyJWT = (settingsService: ISettingsService) => {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
const token = req.headers["authorization"];
|
||||
// Make sure a token is provided
|
||||
if (!token) {
|
||||
const error = new AppError({ message: "No token provided", status: 401, service: SERVICE_NAME });
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
// Make sure it is properly formatted
|
||||
if (!token.startsWith(TOKEN_PREFIX)) {
|
||||
const error = new AppError({ message: "Invalid token format", status: 401, service: SERVICE_NAME, method: "verifyJWT" });
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
|
||||
// Verify the token's authenticity
|
||||
const { jwtSecret } = settingsService.getSettings();
|
||||
if (!jwtSecret) {
|
||||
const error = new AppError({ message: "JWT secret not configured", status: 500, service: SERVICE_NAME });
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
jwt.verify(parsedToken, jwtSecret, (err: jwt.VerifyErrors | null, decoded: jwt.JwtPayload | string | undefined) => {
|
||||
if (err) {
|
||||
const error = new AppError({
|
||||
message: err instanceof Error ? err.message : "Failed to authenticate token",
|
||||
status: 401,
|
||||
service: SERVICE_NAME,
|
||||
details: err instanceof Error ? { error: err } : undefined,
|
||||
method: "verifyJWT",
|
||||
});
|
||||
next(error);
|
||||
return;
|
||||
} else if (isUser(decoded)) {
|
||||
req.user = decoded;
|
||||
next();
|
||||
} else {
|
||||
next(new AppError({ message: "Invalid token payload", status: 401, service: SERVICE_NAME, method: "verifyJWT" }));
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextFunction, Request, RequestHandler, Response } from "express";
|
||||
import { IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
export const createVerifyStatusPageAccess = (statusPagesRepository: IStatusPagesRepository, verifyJWT: RequestHandler) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const url = Array.isArray(req.params.url) ? req.params.url[0] : req.params.url;
|
||||
if (!url) {
|
||||
throw new AppError({ message: "Status page URL is required", status: 400 });
|
||||
}
|
||||
const statusPage = await statusPagesRepository.findByUrl(url);
|
||||
if (statusPage.isPublished) {
|
||||
next(); // Published — no auth needed
|
||||
} else {
|
||||
verifyJWT(req, res, next); // Unpublished — require JWT
|
||||
}
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Router, RequestHandler } from "express";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import multer from "multer";
|
||||
import { IAuthController } from "@/api/controllers/authController.js";
|
||||
|
||||
const upload = multer();
|
||||
|
||||
class AuthRoutes {
|
||||
private router: Router;
|
||||
private authController: IAuthController;
|
||||
|
||||
constructor(authController: IAuthController, verifyJWT: RequestHandler) {
|
||||
this.router = Router();
|
||||
this.authController = authController;
|
||||
this.initRoutes(verifyJWT);
|
||||
}
|
||||
|
||||
initRoutes(verifyJWT: RequestHandler) {
|
||||
this.router.post("/register", upload.single("profileImage"), this.authController.registerUser);
|
||||
this.router.post("/login", this.authController.loginUser);
|
||||
|
||||
this.router.post("/recovery/request", this.authController.requestRecovery);
|
||||
this.router.post("/recovery/validate", this.authController.validateRecovery);
|
||||
this.router.post("/recovery/reset/", this.authController.resetPassword);
|
||||
|
||||
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
|
||||
|
||||
this.router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), this.authController.getAllUsers);
|
||||
this.router.post("/users", verifyJWT, isAllowed(["superadmin"]), upload.single("profileImage"), this.authController.createUser);
|
||||
this.router.get("/users/:userId", verifyJWT, isAllowed(["admin", "superadmin"]), this.authController.getUserById);
|
||||
this.router.patch("/users/:userId", verifyJWT, isAllowed(["superadmin"]), this.authController.editUserById);
|
||||
this.router.patch("/users/:userId/password", verifyJWT, isAllowed(["superadmin"]), this.authController.editUserPasswordById);
|
||||
this.router.delete("/users/:userId", verifyJWT, isAllowed(["admin", "superadmin"]), this.authController.deleteUserById);
|
||||
|
||||
this.router.patch("/user", verifyJWT, upload.single("profileImage"), isAllowed(["admin", "superadmin", "user"]), this.authController.editUser);
|
||||
this.router.delete("/user", verifyJWT, isAllowed(["admin", "superadmin", "user"]), this.authController.deleteUser);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default AuthRoutes;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Router } from "express";
|
||||
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import { ICheckController } from "@/api/controllers/checkController.js";
|
||||
|
||||
class CheckRoutes {
|
||||
private router: Router;
|
||||
private checkController: ICheckController;
|
||||
|
||||
constructor(checkController: ICheckController) {
|
||||
this.router = Router();
|
||||
this.checkController = checkController;
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId);
|
||||
this.router.get("/team", this.checkController.getChecksByTeam);
|
||||
this.router.delete("/team", isAllowed(["admin", "superadmin"]), this.checkController.deleteChecksByTeamId);
|
||||
this.router.get("/:monitorId", this.checkController.getChecksByMonitor);
|
||||
this.router.delete("/:monitorId", this.checkController.deleteChecks);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default CheckRoutes;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { RequestHandler, Router } from "express";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import { IDiagnosticController } from "@/api/controllers/diagnosticController.js";
|
||||
|
||||
class DiagnosticRoutes {
|
||||
private router: Router;
|
||||
private diagnosticController: IDiagnosticController;
|
||||
|
||||
constructor(diagnosticController: IDiagnosticController, verifyJWT: RequestHandler) {
|
||||
this.router = Router();
|
||||
this.diagnosticController = diagnosticController;
|
||||
this.initRoutes(verifyJWT);
|
||||
}
|
||||
|
||||
initRoutes(verifyJWT: RequestHandler) {
|
||||
this.router.get("/system", verifyJWT, isAllowed(["admin", "superadmin"]), this.diagnosticController.getSystemStats);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default DiagnosticRoutes;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { IGeoCheckController } from "@/api/controllers/geoCheckController.js";
|
||||
import { Router } from "express";
|
||||
|
||||
class GeoCheckRoutes {
|
||||
private router: Router;
|
||||
private geoCheckController: IGeoCheckController;
|
||||
|
||||
constructor(geoCheckController: IGeoCheckController) {
|
||||
this.router = Router();
|
||||
this.geoCheckController = geoCheckController;
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/:monitorId", this.geoCheckController.getGeoChecksByMonitor);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default GeoCheckRoutes;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Router } from "express";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import { IIncidentController } from "@/api/controllers/incidentController.js";
|
||||
|
||||
class IncidentRoutes {
|
||||
private router: Router;
|
||||
private incidentController: IIncidentController;
|
||||
|
||||
constructor(incidentController: IIncidentController) {
|
||||
this.router = Router();
|
||||
this.incidentController = incidentController;
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
// Team routes
|
||||
this.router.get("/team", this.incidentController.getIncidentsByTeam);
|
||||
this.router.get("/team/summary", this.incidentController.getIncidentSummary);
|
||||
|
||||
// Individual incident routes
|
||||
this.router.get("/:incidentId", this.incidentController.getIncidentById);
|
||||
this.router.put("/:incidentId/resolve", isAllowed(["admin", "superadmin"]), this.incidentController.resolveIncidentManually);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default IncidentRoutes;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { RequestHandler, Router } from "express";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import { IInviteController } from "@/api/controllers/inviteController.js";
|
||||
|
||||
class InviteRoutes {
|
||||
private router: Router;
|
||||
private inviteController: IInviteController;
|
||||
|
||||
constructor(inviteController: IInviteController, verifyJWT: RequestHandler) {
|
||||
this.router = Router();
|
||||
this.inviteController = inviteController;
|
||||
this.initRoutes(verifyJWT);
|
||||
}
|
||||
|
||||
initRoutes(verifyJWT: RequestHandler) {
|
||||
this.router.post("/send", verifyJWT, isAllowed(["admin", "superadmin"]), this.inviteController.sendInviteEmail);
|
||||
this.router.post("/verify", this.inviteController.verifyInviteToken);
|
||||
this.router.post("/", verifyJWT, isAllowed(["admin", "superadmin"]), this.inviteController.getInviteToken);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default InviteRoutes;
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Router } from "express";
|
||||
import { isAllowed } from "@/api/middleware/isAllowed.js";
|
||||
import { ILogController } from "@/api/controllers/logController.js";
|
||||
class LogRoutes {
|
||||
private router: Router;
|
||||
private logController: ILogController;
|
||||
|
||||
constructor(logController: ILogController) {
|
||||
this.router = Router();
|
||||
this.logController = logController;
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.get("/", isAllowed(["admin", "superadmin"]), this.logController.getLogs);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default LogRoutes;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { IMaintenanceWindowController } from "@/api/controllers/maintenanceWindowController.js";
|
||||
import { Router } from "express";
|
||||
|
||||
class MaintenanceWindowRoutes {
|
||||
private router: Router;
|
||||
private mwController: IMaintenanceWindowController;
|
||||
|
||||
constructor(maintenanceWindowController: IMaintenanceWindowController) {
|
||||
this.router = Router();
|
||||
this.mwController = maintenanceWindowController;
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.post("/", this.mwController.createMaintenanceWindows);
|
||||
this.router.get("/team/", this.mwController.getMaintenanceWindowsByTeamId);
|
||||
|
||||
this.router.get("/monitor/:monitorId", this.mwController.getMaintenanceWindowsByMonitorId);
|
||||
|
||||
this.router.get("/:id", this.mwController.getMaintenanceWindowById);
|
||||
this.router.patch("/:id", this.mwController.editMaintenanceWindow);
|
||||
this.router.delete("/:id", this.mwController.deleteMaintenanceWindow);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default MaintenanceWindowRoutes;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Router } from "express";
|
||||
import { isAllowed } from "@/api/middleware/isAllowed.js";
|
||||
import { IMonitorController } from "@/api/controllers/monitorController.js";
|
||||
|
||||
class MonitorRoutes {
|
||||
private router: Router;
|
||||
private monitorController: IMonitorController;
|
||||
constructor(monitorController: IMonitorController) {
|
||||
this.router = Router();
|
||||
this.monitorController = monitorController;
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
// Team routes
|
||||
this.router.get("/team", this.monitorController.getMonitorsByTeamId);
|
||||
this.router.get("/team/with-checks", this.monitorController.getMonitorsWithChecksByTeamId);
|
||||
this.router.get("/team/groups", this.monitorController.getGroupsByTeamId);
|
||||
|
||||
// Uptime routes
|
||||
this.router.get("/uptime/details/:monitorId", this.monitorController.getUptimeDetailsById);
|
||||
|
||||
// Hardware routes
|
||||
this.router.get("/hardware/details/:monitorId", this.monitorController.getHardwareDetailsById);
|
||||
|
||||
// PageSpeed routes
|
||||
this.router.get("/pagespeed/details/:monitorId", this.monitorController.getPageSpeedDetailsById);
|
||||
|
||||
// Geo checks routes
|
||||
this.router.get("/:monitorId/geo-checks", this.monitorController.getGeoChecksByMonitorId);
|
||||
|
||||
// General monitor routes
|
||||
this.router.post("/pause/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.pauseMonitor);
|
||||
this.router.post("/bulk/pause", isAllowed(["admin", "superadmin"]), this.monitorController.bulkPauseMonitors);
|
||||
|
||||
// Util routes
|
||||
this.router.get("/certificate/:monitorId", (req, res, next) => {
|
||||
this.monitorController.getMonitorCertificate(req, res, next);
|
||||
});
|
||||
|
||||
// General monitor CRUD routes
|
||||
this.router.patch("/notifications", isAllowed(["admin", "superadmin"]), this.monitorController.updateNotifications);
|
||||
this.router.post("/", isAllowed(["admin", "superadmin"]), this.monitorController.createMonitor);
|
||||
this.router.delete("/", isAllowed(["superadmin"]), this.monitorController.deleteAllMonitors);
|
||||
|
||||
// Other static routes
|
||||
this.router.post("/demo", isAllowed(["admin", "superadmin"]), this.monitorController.addDemoMonitors);
|
||||
this.router.get("/export/json", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToJSON);
|
||||
this.router.post("/import/json", isAllowed(["admin", "superadmin"]), this.monitorController.importMonitorsFromJSON);
|
||||
|
||||
this.router.get("/games", this.monitorController.getAllGames);
|
||||
|
||||
// Individual monitor CRUD routes
|
||||
this.router.get("/:monitorId", this.monitorController.getMonitorById);
|
||||
this.router.patch("/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.editMonitor);
|
||||
this.router.delete("/:monitorId", isAllowed(["admin", "superadmin"]), this.monitorController.deleteMonitor);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default MonitorRoutes;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { INotificationController } from "@/api/controllers/notificationController.js";
|
||||
import { Router } from "express";
|
||||
class NotificationRoutes {
|
||||
private router: Router;
|
||||
private notificationController: INotificationController;
|
||||
|
||||
constructor(notificationController: INotificationController) {
|
||||
this.router = Router();
|
||||
this.notificationController = notificationController;
|
||||
this.initializeRoutes();
|
||||
}
|
||||
|
||||
initializeRoutes() {
|
||||
this.router.post("/", this.notificationController.createNotification);
|
||||
|
||||
this.router.post("/test/all", this.notificationController.testAllNotifications);
|
||||
this.router.post("/test", this.notificationController.testNotification);
|
||||
|
||||
this.router.get("/team", this.notificationController.getNotificationsByTeamId);
|
||||
|
||||
this.router.get("/:id", this.notificationController.getNotificationById);
|
||||
this.router.delete("/:id", this.notificationController.deleteNotification);
|
||||
this.router.patch("/:id", this.notificationController.editNotification);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default NotificationRoutes;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Router } from "express";
|
||||
import { isAllowed } from "@/api/middleware/isAllowed.js";
|
||||
import { IJobQueueController } from "@/api/controllers/queueController.js";
|
||||
class QueueRoutes {
|
||||
private router: Router;
|
||||
private queueController: IJobQueueController;
|
||||
|
||||
constructor(queueController: IJobQueueController) {
|
||||
this.router = Router();
|
||||
this.queueController = queueController;
|
||||
this.initRoutes();
|
||||
}
|
||||
initRoutes() {
|
||||
this.router.get("/jobs", isAllowed(["admin", "superadmin"]), this.queueController.getJobs);
|
||||
|
||||
this.router.get("/metrics", isAllowed(["admin", "superadmin"]), this.queueController.getMetrics);
|
||||
this.router.get("/all-metrics", isAllowed(["admin", "superadmin"]), this.queueController.getAllMetrics);
|
||||
this.router.post("/flush", isAllowed(["admin", "superadmin"]), this.queueController.flushQueue);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default QueueRoutes;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Router } from "express";
|
||||
import { isAllowed } from "../middleware/isAllowed.js";
|
||||
import { ISettingsController } from "@/api/controllers/settingsController.js";
|
||||
|
||||
class SettingsRoutes {
|
||||
private router: Router;
|
||||
private settingsController: ISettingsController;
|
||||
|
||||
constructor(settingsController: ISettingsController) {
|
||||
this.router = Router();
|
||||
this.settingsController = settingsController;
|
||||
this.initRoutes();
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get("/", this.settingsController.getAppSettings);
|
||||
this.router.patch("/", isAllowed(["admin", "superadmin"]), this.settingsController.updateAppSettings);
|
||||
this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.settingsController.sendTestEmail);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default SettingsRoutes;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { IStatusPageController } from "@/api/controllers/statusPageController.js";
|
||||
import { RequestHandler, Router } from "express";
|
||||
import multer from "multer";
|
||||
const upload = multer();
|
||||
|
||||
class StatusPageRoutes {
|
||||
private router: Router;
|
||||
private statusPageController: IStatusPageController;
|
||||
|
||||
constructor(statusPageController: IStatusPageController, verifyJWT: RequestHandler, verifyStatusPageAccess: RequestHandler) {
|
||||
this.router = Router();
|
||||
this.statusPageController = statusPageController;
|
||||
this.initRoutes(verifyJWT, verifyStatusPageAccess);
|
||||
}
|
||||
|
||||
initRoutes(verifyJWT: RequestHandler, verifyStatusPageAccess: RequestHandler) {
|
||||
this.router.get("/team", verifyJWT, this.statusPageController.getStatusPagesByTeamId);
|
||||
|
||||
this.router.post("/", upload.single("logo"), verifyJWT, this.statusPageController.createStatusPage);
|
||||
this.router.put("/:id", upload.single("logo"), verifyJWT, this.statusPageController.updateStatusPage);
|
||||
|
||||
this.router.get("/:url", verifyStatusPageAccess, this.statusPageController.getStatusPageByUrl);
|
||||
this.router.delete("/:id", verifyJWT, this.statusPageController.deleteStatusPage);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default StatusPageRoutes;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { ITagsController } from "@/api/controllers/tagController.js";
|
||||
import { Router } from "express";
|
||||
class TagRoutes {
|
||||
private router: Router;
|
||||
private tagController: ITagsController;
|
||||
|
||||
constructor(tagController: ITagsController) {
|
||||
this.router = Router();
|
||||
this.tagController = tagController;
|
||||
this.initializeRoutes();
|
||||
}
|
||||
|
||||
initializeRoutes() {
|
||||
this.router.post("/", this.tagController.createTag);
|
||||
|
||||
this.router.get("/team", this.tagController.getTagsByTeamId);
|
||||
|
||||
this.router.get("/:id", this.tagController.getTagById);
|
||||
this.router.delete("/:id", this.tagController.deleteTag);
|
||||
this.router.patch("/:id", this.tagController.editTag);
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router;
|
||||
}
|
||||
}
|
||||
|
||||
export default TagRoutes;
|
||||
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
import { passwordPattern, nameValidation, lowercaseEmailValidation } from "./shared.js";
|
||||
import { UserRoles } from "@/domain/users/user.type.js";
|
||||
|
||||
//****************************************
|
||||
// Auth Validations
|
||||
//****************************************
|
||||
|
||||
export const loginValidation = z.object({
|
||||
email: z.email("Must be a valid email address").transform((val) => val.toLowerCase()),
|
||||
password: z.string().min(1, "Password is required"),
|
||||
});
|
||||
|
||||
export const registrationBodyValidation = z.object({
|
||||
firstName: nameValidation,
|
||||
lastName: nameValidation,
|
||||
email: lowercaseEmailValidation,
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.regex(passwordPattern, "Password must contain at least one lowercase letter, one uppercase letter, one number, and one special character"),
|
||||
profileImage: z.any().optional(),
|
||||
inviteToken: z.string().optional().default(""),
|
||||
});
|
||||
|
||||
export const recoveryValidation = z.object({
|
||||
email: z.email("Must be a valid email address"),
|
||||
});
|
||||
|
||||
export const recoveryTokenBodyValidation = z.object({
|
||||
recoveryToken: z.string().min(1, "Recovery token is required"),
|
||||
});
|
||||
|
||||
export const newPasswordValidation = z.object({
|
||||
recoveryToken: z.string().min(1, "Recovery token is required"),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.regex(passwordPattern, "Password must contain at least one lowercase letter, one uppercase letter, one number, and one special character"),
|
||||
confirm: z.string().optional(),
|
||||
});
|
||||
|
||||
export const inviteBodyValidation = z.object({
|
||||
email: z.email("Must be a valid email address"),
|
||||
role: z.array(z.enum(UserRoles)).min(1, "At least one role is required"),
|
||||
teamId: z.string().min(1, "Team ID is required"),
|
||||
});
|
||||
|
||||
export const inviteVerificationBodyValidation = z.object({
|
||||
token: z.string().min(1, "Token is required"),
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from "zod";
|
||||
import { booleanCoercion } from "./shared.js";
|
||||
import { GeoContinents } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import { MonitorTypes } from "@/domain/monitors/monitor.types.js";
|
||||
|
||||
//****************************************
|
||||
// Check Validations
|
||||
//****************************************
|
||||
|
||||
export const getChecksParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const getChecksQueryValidation = z.object({
|
||||
type: z.enum(MonitorTypes).optional(),
|
||||
sortOrder: z.enum(["asc", "desc"]),
|
||||
limit: z.coerce.number().optional(),
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
||||
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
||||
ack: booleanCoercion.optional(),
|
||||
page: z.coerce.number(),
|
||||
rowsPerPage: z.coerce.number(),
|
||||
status: booleanCoercion.optional(),
|
||||
continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(),
|
||||
});
|
||||
|
||||
export const getTeamChecksQueryValidation = z.object({
|
||||
sortOrder: z.enum(["asc", "desc"]),
|
||||
limit: z.coerce.number().optional(),
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
||||
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
||||
ack: booleanCoercion.optional(),
|
||||
page: z.coerce.number(),
|
||||
rowsPerPage: z.coerce.number(),
|
||||
});
|
||||
|
||||
export const deleteChecksParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const getChecksSummaryByTeamIdQueryValidation = z.object({
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
import { booleanCoercion } from "./shared.js";
|
||||
|
||||
//****************************************
|
||||
// Incident Validations
|
||||
//****************************************
|
||||
|
||||
export const getIncidentsByTeamQueryValidation = z.object({
|
||||
sortOrder: z.enum(["asc", "desc"]),
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).default("all"),
|
||||
page: z.coerce.number().int().min(0),
|
||||
rowsPerPage: z.coerce.number().int().min(1),
|
||||
status: booleanCoercion.optional(),
|
||||
monitorId: z.string().optional(),
|
||||
resolutionType: z.enum(["manual", "automatic"]).optional(),
|
||||
});
|
||||
|
||||
export const getIncidentSummaryQueryValidation = z.object({
|
||||
limit: z.coerce.number().int().min(1).optional(),
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Central validation exports
|
||||
*
|
||||
* This file re-exports all validation schemas from their respective modules.
|
||||
* Import from here for convenience: import { loginValidation } from "@/validation";
|
||||
*/
|
||||
|
||||
// Shared utilities
|
||||
export * from "./shared.js";
|
||||
|
||||
// Environment validation
|
||||
export * from "@/config/envValidation.js";
|
||||
|
||||
// Domain-specific validations
|
||||
export * from "./authValidation.js";
|
||||
export * from "./monitorValidation.js";
|
||||
export * from "./checkValidation.js";
|
||||
export * from "./maintenanceWindowValidation.js";
|
||||
export * from "./settingsValidation.js";
|
||||
export * from "./statusPageValidation.js";
|
||||
export * from "./notificationValidation.js";
|
||||
export * from "./userValidation.js";
|
||||
export * from "./incidentValidation.js";
|
||||
export * from "./tagValidation.js";
|
||||
@@ -0,0 +1,92 @@
|
||||
import { z } from "zod";
|
||||
import { booleanCoercion } from "./shared.js";
|
||||
import { DurationUnits } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
|
||||
const dateToString = z.coerce.date().transform((d) => d.toISOString());
|
||||
|
||||
//****************************************
|
||||
// Maintenance Window Validations
|
||||
//****************************************
|
||||
|
||||
export const createMaintenanceWindowBodyValidation = z
|
||||
.object({
|
||||
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
active: z.boolean().optional(),
|
||||
duration: z.number().min(1, "Duration is required"),
|
||||
durationUnit: z.enum(DurationUnits),
|
||||
start: dateToString,
|
||||
end: dateToString,
|
||||
repeat: z.number().min(0, "Repeat must be a non-negative number"),
|
||||
expiry: dateToString.optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, ctx) => {
|
||||
const start = new Date(data.start).getTime();
|
||||
const end = new Date(data.end).getTime();
|
||||
if (end <= start) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "End must be after start",
|
||||
path: ["end"],
|
||||
});
|
||||
}
|
||||
if (data.repeat === 0 && end <= Date.now()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "End must be in the future for one-time maintenance windows",
|
||||
path: ["end"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const getMaintenanceWindowByIdParamValidation = z.object({
|
||||
id: z.string().min(1, "ID is required"),
|
||||
});
|
||||
|
||||
export const getMaintenanceWindowsByTeamIdQueryValidation = z.object({
|
||||
active: booleanCoercion.optional(),
|
||||
page: z.coerce.number().optional(),
|
||||
rowsPerPage: z.coerce.number().optional(),
|
||||
field: z.string().optional(),
|
||||
order: z.enum(["asc", "desc"]).optional(),
|
||||
});
|
||||
|
||||
export const getMaintenanceWindowsByMonitorIdParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const deleteMaintenanceWindowByIdParamValidation = z.object({
|
||||
id: z.string().min(1, "ID is required"),
|
||||
});
|
||||
|
||||
export const editMaintenanceWindowByIdParamValidation = z.object({
|
||||
id: z.string().min(1, "ID is required"),
|
||||
});
|
||||
|
||||
export const editMaintenanceByIdWindowBodyValidation = z
|
||||
.object({
|
||||
active: z.boolean().optional(),
|
||||
name: z.string().optional(),
|
||||
repeat: z.number().optional(),
|
||||
start: dateToString.optional(),
|
||||
end: dateToString.optional(),
|
||||
expiry: dateToString.optional(),
|
||||
monitors: z.array(z.string()).min(1, "At least one monitor is required").optional(),
|
||||
duration: z.number().optional(),
|
||||
durationUnit: z.enum(DurationUnits).optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.start && data.end) {
|
||||
const start = new Date(data.start).getTime();
|
||||
const end = new Date(data.end).getTime();
|
||||
if (end <= start) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "End must be after start",
|
||||
path: ["end"],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { z } from "zod";
|
||||
import { booleanCoercion, dnsHostnameRegex, dnsServerValidation } from "./shared.js";
|
||||
import { GeoContinents } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import {
|
||||
DnsRecordTypes,
|
||||
HttpStatusCodeSet,
|
||||
MonitorMatchMethods,
|
||||
MonitorStatuses,
|
||||
MonitorTypes,
|
||||
PageSpeedStrategies,
|
||||
} from "@/domain/monitors/monitor.types.js";
|
||||
|
||||
const httpStatusCode = z.number().refine((code) => HttpStatusCodeSet.has(code), { message: "Must be a valid HTTP status code" });
|
||||
|
||||
export const getMonitorByIdParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const getMonitorByIdQueryValidation = z.object({
|
||||
status: booleanCoercion.optional(),
|
||||
sortOrder: z.enum(["asc", "desc"]).optional(),
|
||||
limit: z.coerce.number().optional(),
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
||||
numToDisplay: z.coerce.number().optional(),
|
||||
normalize: booleanCoercion.optional(),
|
||||
continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(),
|
||||
});
|
||||
|
||||
export const getMonitorsByTeamIdParamValidation = z.object({});
|
||||
|
||||
export const getMonitorsByTeamIdQueryValidation = z.object({
|
||||
type: z.union([z.enum(MonitorTypes), z.array(z.enum(MonitorTypes))]).optional(),
|
||||
filter: z.union([z.string(), z.literal("")]).optional(),
|
||||
tags: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
});
|
||||
|
||||
export const getMonitorsWithChecksQueryValidation = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).optional(),
|
||||
page: z.coerce.number().int().min(0).optional(),
|
||||
rowsPerPage: z.coerce.number().int().min(1).max(100).optional(),
|
||||
filter: z.union([z.string(), z.literal("")]).optional(),
|
||||
field: z.string().optional(),
|
||||
order: z.enum(["asc", "desc"]).optional(),
|
||||
type: z.union([z.enum(MonitorTypes), z.array(z.enum(MonitorTypes))]).optional(),
|
||||
tags: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
explain: booleanCoercion.optional(),
|
||||
});
|
||||
|
||||
export const getCertificateParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
const refineDnsHostname = (body: { type?: string; url?: string }, ctx: z.RefinementCtx) => {
|
||||
if (body.type === "dns" && body.url && !dnsHostnameRegex.test(body.url)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["url"],
|
||||
message: "Enter a valid domain (e.g. www.example.com)",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const refineStrategyType = (body: { type?: string; strategy?: string }, ctx: z.RefinementCtx) => {
|
||||
if (body.strategy !== undefined && body.type !== undefined && body.type !== "pagespeed") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["strategy"],
|
||||
message: "Strategy is only valid for pagespeed monitors",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const createMonitorBodyValidation = z
|
||||
.object({
|
||||
_id: z.string().optional(),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
description: z.union([z.string(), z.literal("")]).optional(),
|
||||
type: z.enum(MonitorTypes, "Invalid monitor type"),
|
||||
statusWindowSize: z.number().min(1).max(20).default(5),
|
||||
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
||||
url: z.string().min(1, "URL is required"),
|
||||
ignoreTlsErrors: z.boolean().default(false),
|
||||
useAdvancedMatching: z.boolean().default(false),
|
||||
port: z.number().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
interval: z.number().optional(),
|
||||
cpuAlertThreshold: z.number().optional(),
|
||||
memoryAlertThreshold: z.number().optional(),
|
||||
diskAlertThreshold: z.number().optional(),
|
||||
tempAlertThreshold: z.number().optional(),
|
||||
notifications: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
customUpCodes: z.array(httpStatusCode).default([]),
|
||||
secret: z.string().optional(),
|
||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
||||
gameId: z.union([z.string(), z.literal("")]).optional(),
|
||||
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
|
||||
strategy: z.enum(PageSpeedStrategies).optional(),
|
||||
selectedDisks: z.array(z.string()).optional(),
|
||||
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
|
||||
geoCheckEnabled: z.boolean().optional(),
|
||||
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
|
||||
geoCheckInterval: z.number().min(300000).optional(),
|
||||
dnsServer: dnsServerValidation.optional(),
|
||||
dnsRecordType: z.enum(DnsRecordTypes).optional(),
|
||||
})
|
||||
.superRefine(refineDnsHostname)
|
||||
.superRefine(refineStrategyType);
|
||||
|
||||
export const editMonitorBodyValidation = z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
type: z.enum(MonitorTypes).optional(),
|
||||
url: z.string().optional(),
|
||||
statusWindowSize: z.number().min(1).max(20).default(5),
|
||||
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
||||
description: z.union([z.string(), z.literal("")]).optional(),
|
||||
interval: z.number().optional(),
|
||||
notifications: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
customUpCodes: z.array(httpStatusCode).optional(),
|
||||
secret: z.string().optional(),
|
||||
ignoreTlsErrors: z.boolean().optional(),
|
||||
useAdvancedMatching: z.boolean().optional(),
|
||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
||||
port: z.number().min(1).max(65535).optional(),
|
||||
cpuAlertThreshold: z.number().optional(),
|
||||
memoryAlertThreshold: z.number().optional(),
|
||||
diskAlertThreshold: z.number().optional(),
|
||||
tempAlertThreshold: z.number().optional(),
|
||||
gameId: z.union([z.string(), z.literal("")]).optional(),
|
||||
grpcServiceName: z.union([z.string(), z.literal("")]).optional(),
|
||||
strategy: z.enum(PageSpeedStrategies).optional(),
|
||||
selectedDisks: z.array(z.string()).optional(),
|
||||
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
|
||||
geoCheckEnabled: z.boolean().optional(),
|
||||
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
|
||||
geoCheckInterval: z.number().min(300000).optional(),
|
||||
dnsServer: dnsServerValidation.optional(),
|
||||
dnsRecordType: z.enum(DnsRecordTypes).optional(),
|
||||
})
|
||||
.superRefine(refineDnsHostname)
|
||||
.superRefine(refineStrategyType);
|
||||
|
||||
export const pauseMonitorParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const bulkPauseMonitorBodyValidation = z.object({
|
||||
monitorIds: z
|
||||
.array(z.string().min(1, "Monitor ID must not be empty"))
|
||||
.min(1, "At least one monitor ID is required")
|
||||
.max(100, "Cannot bulk update more than 100 monitors at once"),
|
||||
pause: z.boolean(),
|
||||
});
|
||||
|
||||
export const getUptimeDetailsByIdParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const getUptimeDetailsByIdQueryValidation = z.object({
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
||||
normalize: booleanCoercion.optional(),
|
||||
});
|
||||
|
||||
const importedMonitorSchema = z
|
||||
.object({
|
||||
id: z.string().optional(),
|
||||
userId: z.string().optional(),
|
||||
teamId: z.string().optional(),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
description: z.union([z.string(), z.literal("")]).optional(),
|
||||
status: z.enum(["up", "down", "paused", "initializing", "maintenance", "breached"]).default("initializing"),
|
||||
statusWindow: z.array(z.boolean()).default([]),
|
||||
statusWindowSize: z.number().min(1).max(20).default(5),
|
||||
statusWindowThreshold: z.number().min(1).max(100).default(60),
|
||||
type: z.enum(MonitorTypes, "Invalid monitor type"),
|
||||
ignoreTlsErrors: z.boolean().default(false),
|
||||
useAdvancedMatching: z.boolean().default(false),
|
||||
jsonPath: z.union([z.string(), z.literal("")]).optional(),
|
||||
expectedValue: z.union([z.string(), z.literal("")]).optional(),
|
||||
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
|
||||
url: z.string().min(1, "URL is required"),
|
||||
port: z.number().optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
interval: z.number().default(60000),
|
||||
uptimePercentage: z.number().optional(),
|
||||
notifications: z.array(z.string()).default([]),
|
||||
tags: z.array(z.string()).default([]),
|
||||
customUpCodes: z.array(httpStatusCode).default([]),
|
||||
secret: z.string().optional(),
|
||||
cpuAlertThreshold: z.number().default(100),
|
||||
cpuAlertCounter: z.number().default(5),
|
||||
memoryAlertThreshold: z.number().default(100),
|
||||
memoryAlertCounter: z.number().default(5),
|
||||
diskAlertThreshold: z.number().default(100),
|
||||
diskAlertCounter: z.number().default(5),
|
||||
tempAlertThreshold: z.number().default(100),
|
||||
tempAlertCounter: z.number().default(5),
|
||||
selectedDisks: z.array(z.string()).default([]),
|
||||
gameId: z.union([z.string(), z.literal("")]).optional(),
|
||||
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
|
||||
strategy: z.enum(PageSpeedStrategies).optional(),
|
||||
group: z.union([z.string().max(50).trim(), z.null()]).default(null),
|
||||
geoCheckEnabled: z.boolean().default(false),
|
||||
geoCheckLocations: z.array(z.enum(GeoContinents)).default([]),
|
||||
geoCheckInterval: z.number().min(300000).default(300000),
|
||||
dnsServer: dnsServerValidation.optional(),
|
||||
dnsRecordType: z.enum(DnsRecordTypes).optional(),
|
||||
createdAt: z.string().optional(),
|
||||
updatedAt: z.string().optional(),
|
||||
})
|
||||
.superRefine(refineDnsHostname)
|
||||
.superRefine(refineStrategyType);
|
||||
|
||||
export const importMonitorsBodyValidation = z.object({
|
||||
monitors: z.array(importedMonitorSchema).min(1, "At least one monitor is required"),
|
||||
});
|
||||
|
||||
export type ImportedMonitor = z.output<typeof importedMonitorSchema>;
|
||||
|
||||
export const getHardwareDetailsByIdParamValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const getHardwareDetailsByIdQueryValidation = z.object({
|
||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
||||
});
|
||||
|
||||
// Canonical monitor shape returned by /monitors endpoints. Keep aligned with
|
||||
// what the controllers actually serialize.
|
||||
export const monitorResponseSchema = z
|
||||
.object({
|
||||
_id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
type: z.enum(MonitorTypes),
|
||||
url: z.string(),
|
||||
port: z.number().optional(),
|
||||
isActive: z.boolean(),
|
||||
interval: z.number(),
|
||||
status: z.enum(MonitorStatuses),
|
||||
statusWindowSize: z.number(),
|
||||
statusWindowThreshold: z.number(),
|
||||
ignoreTlsErrors: z.boolean(),
|
||||
useAdvancedMatching: z.boolean(),
|
||||
jsonPath: z.string().optional(),
|
||||
expectedValue: z.string().optional(),
|
||||
matchMethod: z.enum(MonitorMatchMethods).optional(),
|
||||
notifications: z.array(z.string()),
|
||||
tags: z.array(z.string()),
|
||||
customUpCodes: z.array(httpStatusCode).optional(),
|
||||
secret: z.string().optional(),
|
||||
cpuAlertThreshold: z.number(),
|
||||
memoryAlertThreshold: z.number(),
|
||||
diskAlertThreshold: z.number(),
|
||||
tempAlertThreshold: z.number(),
|
||||
selectedDisks: z.array(z.string()),
|
||||
gameId: z.string().optional(),
|
||||
grpcServiceName: z.string().optional(),
|
||||
group: z.string().nullable().optional(),
|
||||
geoCheckEnabled: z.boolean(),
|
||||
geoCheckLocations: z.array(z.enum(GeoContinents)),
|
||||
geoCheckInterval: z.number(),
|
||||
dnsServer: z.string().optional(),
|
||||
dnsRecordType: z.enum(DnsRecordTypes).optional(),
|
||||
teamId: z.string(),
|
||||
userId: z.string(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
@@ -0,0 +1,148 @@
|
||||
import { z } from "zod";
|
||||
|
||||
//****************************************
|
||||
// Notification Validations
|
||||
//****************************************
|
||||
|
||||
export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
||||
// Email notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("email"),
|
||||
address: z.email("Please enter a valid e-mail address"),
|
||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||
}),
|
||||
// Webhook notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("webhook"),
|
||||
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||
}),
|
||||
// Slack notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("slack"),
|
||||
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||
}),
|
||||
// Discord notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("discord"),
|
||||
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||
}),
|
||||
// PagerDuty notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("pager_duty"),
|
||||
address: z.string().min(1, "PagerDuty integration key is required"),
|
||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||
}),
|
||||
// Matrix notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("matrix"),
|
||||
address: z.union([z.string(), z.literal("")]).optional(),
|
||||
homeserverUrl: z.url({ message: "Please enter a valid Homeserver URL" }),
|
||||
roomId: z.string().min(1, "Room ID is required"),
|
||||
accessToken: z.string().min(1, "Access Token is required"),
|
||||
}),
|
||||
// Teams notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("teams"),
|
||||
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||
}),
|
||||
// Telegram notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("telegram"),
|
||||
address: z.string().min(1, "Chat ID is required"),
|
||||
accessToken: z.string().min(1, "Bot token is required"),
|
||||
}),
|
||||
// Pushover notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("pushover"),
|
||||
address: z.string().min(1, "User key is required"),
|
||||
accessToken: z.string().min(1, "App token is required"),
|
||||
}),
|
||||
// Twilio SMS notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("twilio"),
|
||||
accountSid: z.string().min(1, "Account SID is required"),
|
||||
accessToken: z.string().min(1, "Auth token is required"),
|
||||
phone: z.string().min(1, "Recipient phone number is required"),
|
||||
twilioPhoneNumber: z.string().min(1, "Twilio phone number is required"),
|
||||
}),
|
||||
// ntfy notification
|
||||
z.object({
|
||||
notificationName: z.string().min(1, "Notification name is required"),
|
||||
type: z.literal("ntfy"),
|
||||
address: z.url({ message: "Please enter a valid ntfy server URL" }),
|
||||
topic: z.string().min(1, "Topic is required"),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const testNotificationBodyValidation = createNotificationBodyValidation;
|
||||
|
||||
export const deleteNotificationParamValidation = z.object({
|
||||
id: z.string().min(1, "Notification ID is required"),
|
||||
});
|
||||
export const getNotificationByIdParamValidation = z.object({
|
||||
id: z.string().min(1, "Notification ID is required"),
|
||||
});
|
||||
export const editNotificationParamValidation = z.object({
|
||||
id: z.string().min(1, "Notification ID is required"),
|
||||
});
|
||||
|
||||
export const testAllNotificationsBodyValidation = z.object({
|
||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||
});
|
||||
|
||||
export const sendTestEmailBodyValidation = z.object({
|
||||
to: z.string().min(1, "To field is required"),
|
||||
systemEmailHost: z.string().optional(),
|
||||
systemEmailPort: z.number().optional(),
|
||||
systemEmailSecure: z.boolean().optional(),
|
||||
systemEmailPool: z.boolean().optional(),
|
||||
systemEmailAddress: z.string().optional(),
|
||||
systemEmailDisplayName: z.string().optional(),
|
||||
systemEmailPassword: z.string().optional(),
|
||||
systemEmailUser: z.string().optional(),
|
||||
systemEmailConnectionHost: z.union([z.string(), z.literal("")]).optional(),
|
||||
systemEmailIgnoreTLS: z.boolean().optional(),
|
||||
systemEmailRequireTLS: z.boolean().optional(),
|
||||
systemEmailRejectUnauthorized: z.boolean().optional(),
|
||||
systemEmailTLSServername: z.union([z.string(), z.literal("")]).optional(),
|
||||
});
|
||||
|
||||
export const updateNotificationsValidation = z
|
||||
.object({
|
||||
monitorIds: z.array(z.string()).min(1, "At least one monitor ID is required").max(100, "Cannot update more than 100 monitors at once"),
|
||||
notificationIds: z.array(z.string()).max(100, "Cannot specify more than 100 notification IDs at once"),
|
||||
action: z.enum(["add", "remove", "set"] as const),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.action !== "set" && data.notificationIds.length === 0) return false;
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: "Notification IDs cannot be empty unless action is 'set'",
|
||||
path: ["notificationIds"],
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const getQueueJobsQueryValidation = z.object({
|
||||
page: z.coerce.number().int().min(0).optional(),
|
||||
rowsPerPage: z.coerce.number().int().min(1).max(100).optional(),
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { CHECK_TTL_SENTINEL } from "@/domain/checks/check.type.js";
|
||||
import { z } from "zod";
|
||||
|
||||
//****************************************
|
||||
// Settings Validations
|
||||
//****************************************
|
||||
|
||||
export const updateAppSettingsBodyValidation = z
|
||||
.object({
|
||||
checkTTL: z.number().int().min(1).max(CHECK_TTL_SENTINEL).optional(),
|
||||
systemEmailPort: z.number().nullable().optional(),
|
||||
pagespeedApiKey: z.string().nullable().optional(),
|
||||
language: z.string().optional(),
|
||||
timezone: z.string().optional(),
|
||||
systemEmailHost: z.string().nullable().optional(),
|
||||
systemEmailAddress: z.string().nullable().optional(),
|
||||
systemEmailDisplayName: z
|
||||
.string()
|
||||
.max(100)
|
||||
.transform((val) => (val.trim() === "" ? null : val.trim()))
|
||||
.nullable()
|
||||
.optional(),
|
||||
systemEmailPassword: z.string().nullable().optional(),
|
||||
systemEmailUser: z.string().nullable().optional(),
|
||||
systemEmailConnectionHost: z.string().nullable().optional(),
|
||||
systemEmailTLSServername: z.string().nullable().optional(),
|
||||
|
||||
showURL: z.boolean().optional(),
|
||||
systemEmailSecure: z.boolean().optional(),
|
||||
systemEmailPool: z.boolean().optional(),
|
||||
systemEmailIgnoreTLS: z.boolean().optional(),
|
||||
systemEmailRequireTLS: z.boolean().optional(),
|
||||
systemEmailRejectUnauthorized: z.boolean().optional(),
|
||||
|
||||
globalThresholds: z
|
||||
.object({
|
||||
cpu: z.number().min(1).max(100).optional(),
|
||||
memory: z.number().min(1).max(100).optional(),
|
||||
disk: z.number().min(1).max(100).optional(),
|
||||
temperature: z.number().min(1).max(150).optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.strip();
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from "zod";
|
||||
import { type UserRole } from "@/domain/users/user.type.js";
|
||||
|
||||
export const passwordPattern =
|
||||
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\-_=+[\]{};:'",.~`|\\/])[A-Za-z0-9!?@#$%^&*()\-_=+[\]{};:'",.~`|\\/]+$/;
|
||||
|
||||
export const passwordValidation = z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.regex(passwordPattern, "Password must contain at least one lowercase letter, one uppercase letter, one number, and one special character");
|
||||
|
||||
export const nameValidation = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(50, "Name must be less than 50 characters")
|
||||
.regex(
|
||||
/^(?=.*[\p{L}\p{Sc}])[\p{L}\p{Sc}\s'\-().]+$/u,
|
||||
"Names must contain at least 1 letter and may only include letters, currency symbols, spaces, apostrophes, hyphens (-), periods (.), and parentheses ()."
|
||||
);
|
||||
|
||||
export const lowercaseEmailValidation = z.email().transform((val) => val.toLowerCase());
|
||||
|
||||
export const dnsServerValidation = z
|
||||
.string()
|
||||
.min(1, "DNS server is required")
|
||||
.refine((v) => z.ipv4().safeParse(v).success || z.ipv6().safeParse(v).success, "Enter a valid IPv4 or IPv6 address (e.g. 8.8.8.8)");
|
||||
|
||||
// Hostname (FQDN) — labels of 1-63 alphanumerics/hyphens separated by dots,
|
||||
// optionally prefixed with `_` for service labels (e.g. _dmarc, _imaps._tcp).
|
||||
// No scheme, port, path, or whitespace. Total length ≤ 253. Kept in sync with
|
||||
// the client-side regex in client/src/Validation/monitor.ts.
|
||||
export const dnsHostnameRegex = /^(?=.{1,253}$)([a-zA-Z0-9_](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/;
|
||||
|
||||
export const booleanCoercion = z.preprocess((val) => {
|
||||
if (val === "true" || val === true) return true;
|
||||
if (val === "false" || val === false) return false;
|
||||
return val; // Let Zod validation handle invalid values
|
||||
}, z.boolean());
|
||||
|
||||
export const roleValidator = (allowedRoles: UserRole[]) => {
|
||||
return z.array(z.custom<UserRole>()).refine((userRoles) => allowedRoles.some((role) => userRoles.includes(role)), {
|
||||
message: `You do not have the required authorization. Required roles: ${allowedRoles.join(", ")}`,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "zod";
|
||||
import { booleanCoercion } from "./shared.js";
|
||||
import { StatusPageTypes, StatusPageThemes, StatusPageThemeModes } from "@/domain/status-pages/status-page.type.js";
|
||||
|
||||
//****************************************
|
||||
// Status Page Validations
|
||||
//****************************************
|
||||
|
||||
export const getStatusPageParamValidation = z.object({
|
||||
url: z.string().min(1, "URL is required"),
|
||||
});
|
||||
|
||||
export const getStatusPageQueryValidation = z.object({
|
||||
type: z.union([z.enum(StatusPageTypes), z.array(z.enum(StatusPageTypes))]).transform((val) => (Array.isArray(val) ? val : [val])),
|
||||
timeFrame: z.coerce.number().optional(),
|
||||
});
|
||||
|
||||
export const createStatusPageBodyValidation = z
|
||||
.object({
|
||||
type: z.union([z.enum(StatusPageTypes), z.array(z.enum(StatusPageTypes))]).transform((val) => (Array.isArray(val) ? val : [val])),
|
||||
companyName: z.string().min(1, "Company name is required"),
|
||||
url: z.string().regex(/^[a-zA-Z0-9_-]+$/, {
|
||||
message: "URL can only contain letters, numbers, underscores, and hyphens",
|
||||
}),
|
||||
timezone: z.string().optional(),
|
||||
color: z.string().optional(),
|
||||
monitors: z.array(z.string().regex(/^[0-9a-fA-F]{24}$/, "Must be a valid monitor ID")).min(1, "At least one monitor is required"),
|
||||
subMonitors: z.array(z.string().regex(/^[0-9a-fA-F]{24}$/)).optional(),
|
||||
deleteSubmonitors: z.boolean().optional(),
|
||||
isPublished: booleanCoercion,
|
||||
showCharts: booleanCoercion.optional(),
|
||||
showUptimePercentage: booleanCoercion,
|
||||
showAdminLoginLink: booleanCoercion.optional(),
|
||||
showInfrastructure: booleanCoercion.optional(),
|
||||
removeLogo: z.union([z.literal("true"), z.literal("false")]).optional(),
|
||||
theme: z.enum(StatusPageThemes).optional(),
|
||||
themeMode: z.enum(StatusPageThemeModes).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const imageValidation = z
|
||||
.object({
|
||||
fieldname: z.string().min(1, "Field name is required"),
|
||||
originalname: z.string().min(1, "Original name is required"),
|
||||
encoding: z.string().min(1, "Encoding is required"),
|
||||
mimetype: z.enum(["image/jpeg", "image/png", "image/jpg"], {
|
||||
message: "File must be a valid image (jpeg, jpg, or png)",
|
||||
}),
|
||||
size: z.number().max(3145728, "File size must be less than 3MB"),
|
||||
buffer: z.instanceof(Buffer, { message: "Buffer is required" }),
|
||||
destination: z.string().optional(),
|
||||
filename: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
})
|
||||
.refine((data) => data.buffer, {
|
||||
message: "Image file is required",
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { z } from "zod";
|
||||
|
||||
//****************************************
|
||||
// Tag Validations
|
||||
//****************************************
|
||||
|
||||
export const createTagBodyValidation = z.object({
|
||||
name: z.string().min(1, "Tag name is required"),
|
||||
color: z
|
||||
.string()
|
||||
.regex(/^#([0-9a-fA-F]{6})$/, "Color must be a 6-digit hex value (e.g. #13715B)")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const editTagBodyValidation = createTagBodyValidation;
|
||||
|
||||
export const getTagByIdParamValidation = z.object({
|
||||
id: z.string().min(1, "Tag ID is required"),
|
||||
});
|
||||
export const editTagParamValidation = z.object({
|
||||
id: z.string().min(1, "Tag ID is required"),
|
||||
});
|
||||
export const deleteTagParamValidation = z.object({
|
||||
id: z.string().min(1, "Tag ID is required"),
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { z } from "zod";
|
||||
import { UserRoles } from "@/domain/users/user.type.js";
|
||||
import { nameValidation, lowercaseEmailValidation, passwordValidation } from "./shared.js";
|
||||
|
||||
//****************************************
|
||||
// User Validations
|
||||
//****************************************
|
||||
|
||||
export const getUserByIdParamValidation = z.object({
|
||||
userId: z.string().min(1, "User ID is required"),
|
||||
});
|
||||
|
||||
export const editUserByIdParamValidation = z.object({
|
||||
userId: z.string().min(1, "User ID is required"),
|
||||
});
|
||||
|
||||
export const editUserByIdBodyValidation = z.object({
|
||||
firstName: nameValidation,
|
||||
lastName: nameValidation,
|
||||
role: z.array(z.enum(UserRoles)).min(1, "At least one role is required"),
|
||||
});
|
||||
|
||||
export const editSuperadminUserByIdBodyValidation = z.object({
|
||||
firstName: nameValidation,
|
||||
lastName: nameValidation,
|
||||
role: z.array(z.enum(UserRoles)).min(1, "At least one role is required"),
|
||||
});
|
||||
|
||||
export const editUserPasswordByIdBodyValidation = z.object({
|
||||
password: passwordValidation,
|
||||
});
|
||||
|
||||
export const createUserBodyValidation = z.object({
|
||||
firstName: nameValidation,
|
||||
lastName: nameValidation,
|
||||
email: lowercaseEmailValidation,
|
||||
password: passwordValidation,
|
||||
role: z.array(z.enum(UserRoles)).min(1, "At least one role is required"),
|
||||
});
|
||||
|
||||
export const editUserBodyValidation = z
|
||||
.object({
|
||||
firstName: nameValidation.optional(),
|
||||
lastName: nameValidation.optional(),
|
||||
email: lowercaseEmailValidation.optional(),
|
||||
profilePicture: z.string().optional(),
|
||||
password: passwordValidation.optional(),
|
||||
newPassword: passwordValidation.optional(),
|
||||
})
|
||||
// Changing a password requires both the current password and the new one.
|
||||
// The service only runs the change-password flow when both are present, so
|
||||
// reject a half-filled request
|
||||
.refine((data) => (data.password === undefined) === (data.newPassword === undefined), {
|
||||
message: "Both current password and new password are required to change your password",
|
||||
path: ["newPassword"],
|
||||
});
|
||||
|
||||
// Canonical user shape returned by auth/user endpoints. Keep aligned with what
|
||||
// the controllers actually serialize (password is intentionally omitted).
|
||||
export const userResponseSchema = z
|
||||
.object({
|
||||
_id: z.string(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
email: z.string(),
|
||||
role: z.array(z.string()),
|
||||
teamId: z.string().optional(),
|
||||
profileImage: z.string().nullable().optional(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
Reference in new issue
Block a user